Apache的HttpClient和Java的HttpURLConnection:
自己封裝的網(wǎng)絡(luò)請(qǐng)求類吴裤,第三方的網(wǎng)絡(luò)請(qǐng)求框架都離不開的兩個(gè)類庫(kù)
1.HttpClient:
Android6.0版本直接刪除了HttpClient類庫(kù),采用了OKHttp回俐。
1??簡(jiǎn)要說(shuō)一下HttpClient的GET請(qǐng)求:
(1).創(chuàng)建HttpClient
private HttpClient createHttpClient() {
HttpParams mDefaultHttpParams =newBasicHttpParams();
//設(shè)置連接超時(shí)
HttpConnectionParams.setConnectionTimeout(mDefaultHttpParams,15000);
HttpConnectionParams.setTcpNoDelay(mDefaultHttpParams,true);
HttpProtocolParams.setVersion(mDefaultHttpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(mDefaultHttpParams, HTTP.UTF_8);
//持續(xù)握手
HttpProtocolParams.setUseExpectContinue(mDefaultHttpParams,true);
HttpClient mHttpClient=newDefaultHttpClient(mDefaultHttpParams);
returnmHttpClient;
(2).接下來(lái)創(chuàng)建HttpGet和HttpClient,請(qǐng)求網(wǎng)絡(luò)并得到HttpResponse稀并,并對(duì)HttpResponse進(jìn)行處理:
private void useHttpClientGet(String url) {
HttpGet mHttpGet =newHttpGet(url);
mHttpGet.addHeader("Connection","Keep-Alive");
try{
HttpClient mHttpClient = createHttpClient();
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
HttpEntity mHttpEntity = mHttpResponse.getEntity();
intcode =mHttpResponse.getStatusLine().getStatusCode();
if(null!= mHttpEntity) {
InputStream mInputStream =mHttpEntity.getContent();
String respose =converStreamToString(mInputStream);
Log.i("wangshu","請(qǐng)求狀態(tài)碼:"+ code +"\n請(qǐng)求結(jié)果:\n"+ respose);
mInputStream.close();
}
}catch(IOException e) {
e.printStackTrace();
}
(3).converStreamToString方法將請(qǐng)求結(jié)果轉(zhuǎn)換成String類型:
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;
}
(4).最后我們開啟線程訪問(wèn)百度:
new Thread(new Runnable() {
@Override
public void run() {
useHttpClientGet("http://www.baidu.com");
}
}).start();
返回結(jié)果:
2??.HttpClient的POST請(qǐng)求:
private void useHttpClientPost(String url) {
HttpPost mHttpPost = new HttpPost(url);? ? ? ?
mHttpPost.addHeader("Connection", "Keep-Alive");? ? ? ?
try {? ? ? ? ? ?
HttpClient mHttpClient = createHttpClient();? ? ? ? ?
? ListpostParams = new ArrayList<>();
//要傳遞的參數(shù)
postParams.add(new BasicNameValuePair("username", "moon"));
postParams.add(new BasicNameValuePair("password", "123"));
mHttpPost.setEntity(new UrlEncodedFormEntity(postParams));
HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
HttpEntity mHttpEntity = mHttpResponse.getEntity();
int code = mHttpResponse.getStatusLine().getStatusCode();
if (null != mHttpEntity) {
InputStream mInputStream = mHttpEntity.getContent();
String respose = converStreamToString(mInputStream);
Log.i("wangshu", "請(qǐng)求狀態(tài)碼:" + code + "\n請(qǐng)求結(jié)果:\n" + respose);
mInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}}
2.HttpURLConnection:
在Android 6.0版本中鲫剿,HttpClient庫(kù)被移除了,HttpURLConnection則是以后我們唯一的選擇稻轨。
HttpURLConnection的POST請(qǐng)求:
會(huì)了HttpURLConnection的POST請(qǐng)求那GET請(qǐng)求也就會(huì)了灵莲,所以我這里只舉出POST的例子:
(1).首先我們創(chuàng)建一個(gè)UrlConnManager類,然后里面提供getHttpURLConnection()方法用于配置默認(rèn)的參數(shù)并返回HttpURLConnection:
public static HttpURLConnection getHttpURLConnection(String url){
HttpURLConnection mHttpURLConnection=null;
try {
URL mUrl=new URL(url);
mHttpURLConnection=(HttpURLConnection)mUrl.openConnection();
//設(shè)置鏈接超時(shí)時(shí)間
mHttpURLConnection.setConnectTimeout(15000);
//設(shè)置讀取超時(shí)時(shí)間
mHttpURLConnection.setReadTimeout(15000);
//設(shè)置請(qǐng)求參數(shù)
mHttpURLConnection.setRequestMethod("POST");
//添加Header
mHttpURLConnection.setRequestProperty("Connection","Keep-Alive");
//接收輸入流
mHttpURLConnection.setDoInput(true);
//傳遞參數(shù)時(shí)需要開啟
mHttpURLConnection.setDoOutput(true);
} catch (IOException e) {
e.printStackTrace();
}
return mHttpURLConnection ;
}
(2).因?yàn)槲覀円l(fā)送POST請(qǐng)求殴俱,所以在UrlConnManager類中再寫一個(gè)postParams()方法用來(lái)組織一下請(qǐng)求參數(shù)并將請(qǐng)求參數(shù)寫入到輸出流中:
public static void postParams(OutputStream output,Listparams List) throws IOException{
StringBuilder mStringBuilder=new StringBuilder();
for (NameValuePair pair:paramsList){
if(!TextUtils.isEmpty(mStringBuilder)){
mStringBuilder.append("&");
}
mStringBuilder.append(URLEncoder.encode(pair.getName(),"UTF-8"));
mStringBuilder.append("=");
mStringBuilder.append(URLEncoder.encode(pair.getValue(),"UTF-8"));
}
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));
writer.write(mStringBuilder.toString());
writer.flush();
writer.close();
}
(3).接下來(lái)我們添加請(qǐng)求參數(shù)政冻,調(diào)用postParams()方法將請(qǐng)求的參數(shù)組織好傳給HttpURLConnection的輸出流,請(qǐng)求連接并處理返回的結(jié)果:
private void useHttpUrlConnectionPost(String url) { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? InputStream mInputStream = null; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? HttpURLConnection mHttpURLConnection = UrlConnManager.getHttpURLConnection(url);? ? ? ? try { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?List postParams = new ArrayList<>();
//要傳遞的參數(shù)
postParams.add(new BasicNameValuePair("username", "moon"));
postParams.add(new BasicNameValuePair("password", "123"));
UrlConnManager.postParams(mHttpURLConnection.getOutputStream(), postParams);
mHttpURLConnection.connect();
mInputStream = mHttpURLConnection.getInputStream();
int code = mHttpURLConnection.getResponseCode();
String respose = converStreamToString(mInputStream);
Log.i("buxq", "請(qǐng)求狀態(tài)碼:" + code + "\n請(qǐng)求結(jié)果:\n" + respose);
mInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
(4).最后開啟線程請(qǐng)求網(wǎng)絡(luò):
private void useHttpUrlConnectionGetThread() {
new Thread(new Runnable() {
@Override
public void run() {
useHttpUrlConnectionPost("http://www.baidu.com");
}
}).start();
}