Android 网络请求
##HttpClient (Apache)
6.0中已经移除了这个方法,Google建议使用HttpUrlConnection 见Android 6.0 Changes
###GET 方法
新建一个HttpGet对象
1
HttpGet httpGet = new HttpGet("https://baidu.com");
获取HtttpClient实例
1
HttpClient httpClient = new DefaultHttpClient();
获取HttpResponse实例 并传入HttpGet对象
1
HttpResponse response = httpClient.execute(httpGet);
判断是否请求成功
1
2
3
4
5
6if(response.getStatusLine().getStatusCode()==200)
{//do something
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity);
String result = EntityUtils.toString(response.getEntity(),"UTF-8");//带中文的话
}
POST 方法
新建一个HttpGet对象
1
HttpGet httpPost = new HttpPost("https://baidu.com");
获取HtttpClient实例
1
HttpClient httpClient = new DefaultHttpClient();
设置POST参数(1)
1
2
3
4
5
6List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "username"));
params.add(new BasicNameValuePair("password", "password"));
//添加内容到请求中
UrlEncodedFormEntity entity = new UrlEncodedFromEntity(params,"UTF-8");
httpPost.setEntity(entity);设置POST参数(2)
1
2
3
4
5
6
7NameValuePair namePair = new BasicNameValuePair("username","username");
NameValuePair pswPair = new BasicNameValuePair("password","password");
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
pariList.add(namePair);
//添加内容到请求中
HttpEntity httpEntity = new UrlEncodedFormEntity(pairlist);
httpPost.setEntity(httpEntity);获取HttpResponse实例 并传入HttpGet对象
1
HttpResponse response = httpClient.execute(httpPost);
判断是否请求成功
1
2
3
4
5
6if(response.getStatusLine().getStatusCode()==200)
{//do something
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity);
//String result = EntityUtils.toString(response.getEntity(),”UTF-8”);//带中文的话
}
GET 方法
- 先new一个Url 对象,并传入网址
1
Url url = new Url("https://baidu.com");
- 打开一个HttpUrlConnection连接
1
HttpUrlConnection httpUrlConnection = (HttpUrlConnection) url.openConnection();
- 设置get或者post方法
1
httpUrlConnection.setRequestMethod(“GET”);
- 定制一些信息 比如超时时间,title等
- 调用getInputStream 获取服务器返回的输入流
1
2
3
4
5
6
7
8InputStream in = httpUrlConnection.getInputStream();
//对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
} - 关闭连接
1
httpUrlConnection.disconnect();
POST 方法
- 前面都一样
1
2
3httpUrlConnection.setRequestMethod("POST");
DataOutputStream dataOutputStream = new DataOutputStream(httpUrlConnection.getOutputStream);
dataOutputStream.writeBytes("username=XXX&password=YYY");