文中使用的jar包有:commons-codec-1.9、commons-logging-1.2、httpclient-4.5.9、httpcore-4.4.11、httpmime-4.5.9
相關jar包下載可以直接去官網下載HTTPCLIENT的包
文中相關頭信息寫的不多,可以去上一篇文章“Java實現HTTP請求GET和POST之HttpURLConnection”中看
文中一些代碼也是網上東摘西錄的,這裏僅作爲一個模板思路參考,功能並不複雜
一、GET請求
public static void sumitGet() {
//創建httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//創建httpGet對象
HttpGet httpGet = new HttpGet("https://www.baidu.com");
System.out.println("executing request " + httpGet.getURI());
//設置頭信息
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
CloseableHttpResponse response = null;
try {
//執行Get請求
response = httpClient.execute(httpGet);
//獲取返回的全部頭信息
Header headers[] = response.getAllHeaders();
//獲取響應實體
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
//處理響應實體
if(entity != null) {
System.out.println("長度:" + entity.getContentLength());
System.out.println("內容:" + EntityUtils.toString(entity, "gbk"));
}
response.close();
httpClient.close();
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
二、POST請求,參數模擬登錄
public static void submitPost() {
//創建httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//創建HttpPost對象
HttpPost post = new HttpPost("https://api.douban.com/v2/book/1220562");
//設置POST請求傳遞參數
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "test"));
params.add(new BasicNameValuePair("password", "12356"));
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"UTF-8");
post.setEntity(entity);
System.out.println("executing request " + post.getURI());
//執行請求並處理響應
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity entity2 = response.getEntity();
if (entity2 != null){
System.out.println("響應內容:");
System.out.println(EntityUtils.toString(entity2));
}
response.close();
httpClient.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
三、POST請求,參數格式JSON
public void test3() {
try {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
Map<String, Object> data = new HashMap<String, Object>();
data.put("code", "001");
data.put("name", "測試");
HttpPost httpPost = new HttpPost("www.baidu.com/test2");
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
httpPost.setEntity(new StringEntity("",
ContentType.create("text/json", "UTF-8")));
client = HttpClients.createDefault();
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println(result);
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
四、上傳文件
public static void upload() {
//創建CloseableHttpClient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//創建HttpPost對象
HttpPost httppost = new HttpPost("http://www.baidu.com/upFile.action");
//官方API解釋爲由文件支持的二進制正文部分
FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
//官方API解釋爲由字節數組支持的文本正文部分
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
//可以用HTTP消息發送h或接收的實體
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
response.close();
httpclient.close();
}catch (Exception e) {
e.printStackTrace();
}
}