我是Android開發新手,直到現在我正在使用DefaultHttpClient進行服務調用,現在我需要使用HttpURlConnection作爲DefaultHttpClient被取消。我怎樣才能做到這一點?從DefaultHttpClient更改爲HttpURLConnection
我對DefaultHttpClient代碼是
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Constant.statusCode = httpResponse.getStatusLine().getStatusCode();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
我打電話,我的AsyncTask的doInBackground這種方法
ServiceHandler serviceHandler = new ServiceHandler();
String jsonResponse = serviceHandler.makeServiceCall(url, serviceHandler.POST, pairs);
檢查此參考:http://www.tutorialspoint.com/android/android_network_connection.htm –