android用 HttpClient向服务器发起GET或者POST请求:
首先client参数设置(可选设置,设置超时):
private HttpClient httpclient;
private HttpPost httppost;
private HttpParams httpParameters;
private int timeoutConnection = 5*1000;
private int timeoutSocket = 10*1000;
public WidsetsHttpClient() {
// Set the timeout in
milliseconds until a connection is established.
httpParameters = new BasicHttpParams();
// Set the default socket timeout (SO_TIMEOUT)
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpclient = new DefaultHttpClient(httpParameters);
httppost = new HttpPost(Display.serviceAPI);
}
1. GET:
//先将参数放入List,再对参数进行URL编码
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
//对参数编码
String param = URLEncodedUtils.format(params, "UTF-8");
//请求的 地址Url
String baseUrl = "http://ubs.free4lab.com/php/method.php";
//将URL与参数拼接,拼地址
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);
//默认参数
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //发起GET请求
//获取响应码返回200表示成功
int resCode = response.getStatusLine().getStatusCode()
Log.i(TAG, "resCode = " +resCode );
//获取服务器响应内容:字符串
String result = EntityUtils.toString(response.getEntity(), "utf-8");
Log.i(TAG, "result = " + result );
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
POST:
//和GET方式一样,先将参数放入List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
try {
HttpPost postMethod = new HttpPost(baseUrl);
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(postMethod); //执行POST方法
//获取响应码返回200表示成功
int resCode = response.getStatusLine().getStatusCode()
Log.i(TAG, "resCode = " +resCode );
//获取服务器响应内容:字符串
String result = EntityUtils.toString(response.getEntity(), "utf-8");
Log.i(TAG, "result = " + result );
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}