0
在我的程序中,我使用postmethod來調用Web服務。但Web服務基於Get方法。我不知道如何編寫Get方法的代碼。請告訴我如何編寫Get方法的代碼來調用Web服務。我的代碼如下所示基於post方法。如何在android中使用Get方法調用Web服務
RestClient arc = new RestClient(「http:..............」); arc.AddParam(「search」,msft);
在這裏,我通過調用AddParam method.The RESTClient實現類創建的對象RESTClient實現並添加參數是
公共類AddSubRestClient {
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private InputStream instream;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public InputStream inResponse() {
return instream;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public AddSubRestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute() throws Exception
{
//Postmethod
HttpPost request = new HttpPost(url);
Log.e("in","rest client");
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty()){
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(params,HTTP.UTF_8);
request.setEntity(p_entity);
Log.e("params",params.toString());
Log.e("request",request.toString());
}
executeRequest(request, url);
}
public void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
intream = entity.getContent();
response = convertStreamToString(instream);
/Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
Log.e("in","try block");
line = reader.readLine();
Log.e("line",line);
if(line==null)
{
Log.e("Line","is null");
}
else{
Log.e("Line","is not null");
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
Log.e("line","close");
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
所以請告訴我怎麼寫代替get方法代替post方法或告訴我解決方案
提前謝謝
請參閱我的相關問題:http://stackoverflow.com/questions/30092261/using-volley-library-inside-a-library – 2015-05-07 05:04:20