目录
HttpClient 和 HttpURLConnection
HttpClient 和 HttpURLConnection
1、Android网络访问简介
在android移动端访问网络资源会接触到两个类HttpClient 和 HttpURLConnection
在android2.2和之前的版本会使用HttpClient,但是在android2.3之后一般使用HttpURLConnection,HttpClient是Apache的一个开源库。
从Android6.0这个版本Android SDK删除了HttpClient的类库,如果开发者想使用这个类库可以在build.gradle中添加一下代码来引入该类库:
android {
...
useLibrary 'org.apache.http.legacy'
}
注意在android中使用网络请求的时候不要忘记在清单文件中申请权限
<uses-permission android:name="android.permission.INTERNET"/>
1、HttpClient
下面是我们使用HttpClient的例子,AndroidHttpClient实际上继承HttpClient,我们这里使用AndroidHttpClient来实践。
public final class AndroidHttpClient implements HttpClient;
1.1、使用HttpClient实践GET请求
private AndroidHttpClient createHttpClient() {
AndroidHttpClient androidHttpClient = AndroidHttpClient.newInstance("");
HttpParams httpParams = androidHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 15000);//设置连接超时
HttpConnectionParams.setSoTimeout(httpParams, 15000);//设置请求超时
HttpConnectionParams.setTcpNoDelay(httpParams, true);
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
HttpProtocolParams.setUseExpectContinue(httpParams, true);
return androidHttpClient;
}
private String converStreamToString(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String respose = sb.toString();
return respose;
}
private void httpGet(String url) {
HttpGet mHttpGet = new HttpGet(url);
mHttpGet.addHeader("Connection", "Keep-Alive");
try {
AndroidHttpClient httpClient = createHttpClient();
HttpResponse httpResponse = httpClient.execute(mHttpGet);
HttpEntity httpEntity = httpResponse.getEntity();
int code = httpResponse.getStatusLine().getStatusCode();
if (httpEntity != null) {
InputStream is = httpEntity.getContent();
String response = converStreamToString(is);
Log.i("#请求结果#", "code:" + code + "\n response:" + response);
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void doGet() {
new Thread(new Runnable() {
@Override
public void run() {
httpGet("http://api.k780.com/?app=weather.history&weaid=1&date=2015-07-20&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json");
}
}).start();
}
1.2、使用HttpClient实践POSt请求
private void httpPost(String url) {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Connection", "Keep-Alive");
try {
HttpClient httpClient = createHttpClient();
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("weaid", "1"));
params.add(new BasicNameValuePair("date", "2015-07-20"));
params.add(new BasicNameValuePair("appkey", "10003"));
params.add(new BasicNameValuePair("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4"));
params.add(new BasicNameValuePair("format", "json"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
int code = httpResponse.getStatusLine().getStatusCode();
if (httpEntity != null) {
InputStream is = httpEntity.getContent();
String response = converStreamToString(is);
Log.i("#请求结果#", "code:" + code + "\n response:" + response);
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void doPost() {
new Thread(new Runnable() {
@Override
public void run() {
//http://api.k780.com/?app=weather.history&weaid=1&date=2015-07-20&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
httpPost("http://api.k780.com/?app=weather.history");
}
}).start();
}
2、HttpURLConnection
首先封装一个管理类UrlConnectionMananger
public class UrlConnectionMananger {
public static HttpURLConnection getHttpURLConnection(String urlStr) {
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(30000);//设置连接超时
httpURLConnection.setReadTimeout(30000);//设置读取超时
httpURLConnection.setRequestMethod("POST");//设置请求方式
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");//设置头
httpURLConnection.setDoInput(true);//接收输入流
httpURLConnection.setDoOutput(true);//通过url进行输出
} catch (IOException e) {
e.printStackTrace();
}
return httpURLConnection;
}
public static void postParams(OutputStream outputStream, List<NameValuePair> paramsList) throws IOException {
StringBuilder builder = new StringBuilder();
for (NameValuePair nameValuePair : paramsList) {
if (!TextUtils.isEmpty(builder)) {
builder.append("&");
}
builder.append(URLEncoder.encode(nameValuePair.getName(),"UTF-8"));
builder.append("=");
builder.append(URLEncoder.encode(nameValuePair.getValue(),"UTF-8"));
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
Log.i("#######",builder.toString());
writer.write(builder.toString());
writer.flush();
writer.close();
}
然后在Activity中使用,这里使用HttpURLConnection做POST请求
private void useHttpPost(String url) {
InputStream inputStream = null;
HttpURLConnection httpURLConnection = UrlConnectionMananger.getHttpURLConnection(url);
try {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("weaid", "1"));
params.add(new BasicNameValuePair("date", "2015-07-20"));
params.add(new BasicNameValuePair("appkey", "10003"));
params.add(new BasicNameValuePair("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4"));
params.add(new BasicNameValuePair("format", "json"));
UrlConnectionMananger.postParams(httpURLConnection.getOutputStream(),params);
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
int code = httpURLConnection.getResponseCode();
String response = converStreamToString(inputStream);
Log.i("#请求结果#", "code:" + code + "\n response:" + response);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void doHttpConnectionPost() {
new Thread(new Runnable() {
@Override
public void run() {
useHttpPost("http://api.k780.com/?app=weather.history");
}
}).start();
}
调用doHttpConnectionPost()测试
请求结果打印部分如下,上面的get和post请求用的同一个url,都是支持的
code: 200
response: {
"success": "1",
"result": [{
"weaid": "1",
"week": "星期一",
"cityno": "beijing",
"citynm": "北京",
"cityid": "101010100",
"uptime": "2015-07-20 00:50:00",
"temperature": "22℃",
"humidity": "97%",
"aqi": "101",
"weather": "晴",
"weather_icon": "http://api.k780.com/upload/weather/d/0.gif",
"wind": "东北风",
"winp": "1级",
"temp": "22",
"weatid": "1",
"windid": "13",
"winpid": "201",
"weather_iconid": "0"
}, {
"weaid": "1",
"week": "星期一",
"cityno": "beijing",
"citynm": "北京",
"cityid": "101010100",
"uptime": "2015-07-20 01:50:00",
"temperature": "22℃",
"humidity": "99%",
"aqi": "102",
"weather": "晴",
"weather_icon": "http://api.k780.com/upload/weather/d/0.gif",
"wind": "东北风",
"winp": "1级",
"temp": "22",
"weatid": "1",
"windid": "13",
"winpid": "201",
"weather_iconid": "0"
}]
上面使用HttpURLConnection实践了POST请求,GET请求也是一样,只需修改
httpURLConnection.setRequestMethod("GET");即可
public static HttpURLConnection getHttpURLConnection(String urlStr) {
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(30000);//设置连接超时
httpURLConnection.setReadTimeout(30000);//设置读取超时
httpURLConnection.setRequestMethod("GET");//设置请求方式
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");//设置头
httpURLConnection.setDoInput(true);//接收输入流
httpURLConnection.setDoOutput(true);//通过url进行输出
} catch (IOException e) {
e.printStackTrace();
}
return httpURLConnection;
}