一、HttpClient簡介
HttpClient是Apache組織發佈的開源HTTP客戶端庫,它支持多線程連接、連接池、SSL、Cookie等特性。Python、Java、C#、C++等多個語言都有HttpClient的實現,本文介紹的是在Android平台上使用HttpClient發送HTTP請求。
二、HttpClient使用流程
HttpClient的使用流程大致如下:
// 創建HttpClient對象,設置連接池和Cookie存儲
HttpClient httpClient = new DefaultHttpClient();
httpClient.setConnPoolTimeout(30 * 1000); // 設置連接超時時間
httpClient.setSoTimeout(30 * 1000); // 設置讀取超時時間
httpClient.setCookieStore(new BasicCookieStore()); // 設置Cookie存儲
// 創建Http請求對象
HttpPost httpPost = new HttpPost(url);
// 設置請求參數
List params = new ArrayList();
params.add(new BasicNameValuePair("username", "test"));
params.add(new BasicNameValuePair("password", "123456"));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
// 執行Http請求,獲取響應對象
HttpResponse response = httpClient.execute(httpPost);
// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
上述代碼通過創建HttpClient對象、創建Http請求對象、設置請求參數、執行Http請求、解析響應結果等步驟來發送HTTP請求。
三、發送GET請求
使用HttpClient發送GET請求也比較簡單,只需要使用HttpGet對象替換HttpPost對象,並傳入請求參數即可。
// 創建Http請求對象 HttpGet httpGet = new HttpGet(url + "?param=123"); // 執行Http請求,獲取響應對象 HttpResponse response = httpClient.execute(httpGet); // 解析響應結果 String result = EntityUtils.toString(response.getEntity(), "UTF-8");
四、發送文件
使用HttpClient發送文件需要使用MultipartEntityBuilder對象,它可以添加文件參數、普通參數,可以設置字符編碼,也可以設置進度監聽器。
// 創建Http請求對象
HttpPost httpPost = new HttpPost(url);
// 創建MultipartEntityBuilder對象,設置字符編碼和進度監聽器
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setCharset(Charset.forName("UTF-8"))
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", new FileBody(file, ContentType.DEFAULT_BINARY))
.addTextBody("param1", "value1", ContentType.create("text/plain", Charset.forName("UTF-8")))
.addTextBody("param2", "value2", ContentType.create("text/plain", Charset.forName("UTF-8")))
.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
// 設置請求參數
httpPost.setEntity(builder.build());
// 執行Http請求,獲取響應對象
HttpResponse response = httpClient.execute(httpPost);
// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
五、發送JSON數據
使用HttpClient發送JSON數據需要使用StringEntity對象,它可以設置字符編碼和Content-Type。
// 創建Http請求對象
HttpPost httpPost = new HttpPost(url);
// 設置請求頭和請求參數
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setEntity(new StringEntity(jsonStr, "UTF-8"));
// 執行Http請求,獲取響應對象
HttpResponse response = httpClient.execute(httpPost);
// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
六、完整示例代碼
package com.example.httpclientdemo;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private TextView mResultTv;
private Button mGetBtn;
private Button mPostBtn;
private Button mFileBtn;
private Button mJsonBtn;
private HttpClient mHttpClient;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
mResultTv.setText("GET請求結果:\n" + msg.obj);
break;
case 1:
mResultTv.setText("POST請求結果:\n" + msg.obj);
break;
case 2:
mResultTv.setText("文件上傳請求結果:\n" + msg.obj);
break;
case 3:
mResultTv.setText("JSON請求結果:\n" + msg.obj);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mResultTv = (TextView) findViewById(R.id.result_tv);
mGetBtn = (Button) findViewById(R.id.get_btn);
mPostBtn = (Button) findViewById(R.id.post_btn);
mFileBtn = (Button) findViewById(R.id.file_btn);
mJsonBtn = (Button) findViewById(R.id.json_btn);
// 創建HttpClient對象
PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
connectionManager.setMaxTotal(10);
connectionManager.setDefaultMaxPerRoute(3);
ConnManagerParams.setTimeout(connectionManager.getParams(), 10000);
mHttpClient = new DefaultHttpClient(connectionManager);
mGetBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 發送GET請求
new Thread(new Runnable() {
@Override
public void run() {
Message msg = Message.obtain();
try {
// 創建Http請求對象
HttpGet httpGet = new HttpGet("https://www.baidu.com");
// 執行Http請求,獲取響應對象
HttpResponse response = mHttpClient.execute(httpGet);
// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
msg.what = 0;
msg.obj = result;
} catch (IOException e) {
e.printStackTrace();
msg.obj = e.getMessage();
} finally {
mHandler.sendMessage(msg);
}
}
}).start();
}
});
mPostBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 發送POST請求
new Thread(new Runnable() {
@Override
public void run() {
Message msg = Message.obtain();
try {
// 創建Http請求對象
HttpPost httpPost = new HttpPost("https://www.baidu.com");
// 設置請求參數
List params = new ArrayList();
params.add(new BasicNameValuePair("username", "test"));
params.add(new BasicNameValuePair("password", "123456"));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
// 執行Http請求,獲取響應對象
HttpResponse response = mHttpClient.execute(httpPost);
// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
msg.what = 1;
msg.obj = result;
} catch (IOException e) {
e.printStackTrace();
msg.obj = e.getMessage();
} finally {
mHandler.sendMessage(msg);
}
}
}).start();
}
});
mFileBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 發送文件請求
new Thread(new Runnable() {
@Override
public void run() {
Message msg = Message.obtain();
try {
// 創建Http請求對象
HttpPost httpPost = new HttpPost("http://www.example.com/upload");
// 創建MultipartEntityBuilder對象,設置字符編碼和進度監聽器
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setCharset(Charset.forName("UTF-8"))
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", new FileBody(new File("/sdcard/Download/test.jpg"), ContentType.DEFAULT_BINARY))
.addTextBody("name", "test", ContentType.create("text/plain", Charset.forName("UTF-8")))
.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
// 設置請求參數
httpPost.setEntity(builder.build());
// 執行Http請求,獲取響應對象
HttpResponse response = mHttpClient.execute(httpPost);
// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
msg.what = 2;
msg.obj = result;
} catch (IOException e) {
e.printStackTrace();
msg.obj = e.getMessage();
} finally {
mHandler.sendMessage(msg);
}
}
}).start();
}
});
mJsonBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 發送JSON請求
new Thread(new Runnable() {
@Override
public void run() {
Message msg = Message.obtain();
try {
// 創建Http請求對象
HttpPost httpPost = new HttpPost("http://www.example.com/json");
// 設置請求頭和請求參數
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
String jsonStr = "{\"name\":\"test\",\"age\":18}";
httpPost.setEntity(new StringEntity(jsonStr, "UTF-8"));
// 執行Http請求,獲取響應對象
HttpResponse response = mHttpClient.execute(httpPost);
// 解析響應結果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
msg.what = 3;
msg.obj = result;
} catch (IOException e) {
e.printStackTrace();
msg.obj = e.getMessage();
} finally {
mHandler.sendMessage(msg);
}
}
}).start();
}
});
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/300497.html
微信掃一掃
支付寶掃一掃