1.HttpClient
1.1 Get
//先将参数放入List,再对参数进行URL编码
List<BasicNameValuePair> params =
new
LinkedList<BasicNameValuePair>();
params.add(
new
BasicNameValuePair(
"param1"
,
"中国"
));
params.add(
new
BasicNameValuePair(
"param2"
,
"value2"
));
//对参数编码
String param = URLEncodedUtils.format(params,
"UTF-8"
);
//baseUrl
//将URL与参数拼接
HttpGet getMethod =
new
HttpGet(baseUrl +
"?"
+ param);
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch
(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
1.2 Host
//和GET方式一样,先将参数放入List
params =
new
LinkedList<BasicNameValuePair>();
params.add(
new
BasicNameValuePair(
"param1"
,
"Post方法"
));
params.add(
new
BasicNameValuePair(
"param2"
,
"第二个参数"
));
try
{
HttpPost postMethod =
new
HttpPost(baseUrl);
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch
(ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch
(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2.HttpURLConnection
1)创建一个URL对象
URL url = new URL(http://www.baidu.com);
2)利用HttpURLConnection对象从网络中获取网页数据
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
3)设置连接超时
conn.setConnectTimeout(6*1000);
4)对响应码进行判断
if (conn.getResponseCode() != 200) //从Internet获取网页,发送请求,将网页以流的形式读回来
throw new RuntimeException("请求url失败");
5)得到网络返回的输入流
InputStream is = conn.getInputStream();
6)String result = readData(is, "GBK"); //文件流输入出文件用outStream.write
7)conn.disconnect();