android http 请求方式
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表示成功
intresCode =response.getStatusLine().getStatusCode()
Log.i(TAG, "resCode = " +resCode);
//获取服务器响应内容:字符串
Stringresult =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);
//获取服务器响应内容:字符串
Stringresult =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();
}
更多相关文章
- angularjs是怎么为ng-click事件传递参数的?
- 解决 ASP.NET Core MySql varchar 字符串截取实例教程
- C#中SQL参数传入空值出错误和如何解决办法
- 字符串分割的使用实例代码
- 在iis上运行的服务器端程序,运行一段时间后,访问都只出现一行乱码,
- 分享html元素调用服务器实例
- 详解可选参数和命名参数实例
- C#中如何格式化json字符串的方法分析
- Asp.net MVC 对输入的字符串字段做Trim处理的方法_实用技巧