androidä¸ä½¿ç¨HTTPå°æ°æ®åéå°æå¡å¨ãHTTPå¯ä½¿ç¨androidèªå¸¦çhttpclientæ¡æ¶å®ç°ãæå¡å¨å¾å°è¯·æ±åæ°åå解æå³å¯ã以ä¸æ¯ç¤ºä¾ä»£ç ï¼
1. GET æ¹å¼ä¼ éåæ°
//å
å°åæ°æ¾å
¥Listï¼å对åæ°è¿è¡URLç¼ç
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "æ°æ®")); //å¢å åæ°1
params.add(new BasicNameValuePair("param2", "value2"));//å¢å åæ°2
String param = URLEncodedUtils.format(params, "UTF-8");//对åæ°ç¼ç
String baseUrl = "æå¡å¨æ¥å£å®æ´URL";
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//å°URLä¸åæ°æ¼æ¥
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //åèµ·GET请æ±
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //è·åååºç
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//è·åæå¡å¨ååºå
容
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2. POSTæ¹å¼ æ¹å¼ä¼ éåæ°
//åGETæ¹å¼ä¸æ ·ï¼å
å°åæ°æ¾å
¥List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "Postæ¹æ³"));//å¢å åæ°1
params.add(new BasicNameValuePair("param2", "第äºä¸ªåæ°"));//å¢å åæ°2
try {
HttpPost postMethod = new HttpPost(baseUrl);//å建ä¸ä¸ªpost请æ±
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //å°åæ°å¡«å
¥POST Entityä¸
HttpResponse response = httpClient.execute(postMethod); //æ§è¡POSTæ¹æ³
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //è·åååºç
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //è·åååºå
容
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
温馨提示:内容为网友见解,仅供参考