直接上代碼,項目時maven項目,需要在pom文件中導入代碼中需要引用的jar包;
package com.jokin.learn.HttpTools;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
public class HttpUtil {
private Log logger = LogFactory.getLog(this.getClass());
private static final String pattern = "yyyy-MM-dd HH:mm:ss:SSS";
/**
*實現get請求
* @param baseUrl
* @param parameters 傳入參數的map;當無參數時,傳入的map=null即可
* @param headers 傳入header的map, 例如cookies等,當無值時,傳入null即可
* @return
*/
public String get1(String baseUrl,Map<String, String> parameters ,Map<String, String> headers ){
//創建一個httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//創建一個返回值對象
CloseableHttpResponse response = null;
String entityString=null;
try {
URIBuilder uriBuilder = new URIBuilder(baseUrl);
if(parameters!=null&¶meters.size()>0){
for (Map.Entry<String, String> temp : parameters.entrySet() ) {
//循環map裏面的每一對鍵值對,然後獲取key和value即時想要的參數的 key和value
uriBuilder.addParameter(temp.getKey(),temp.getValue());
}
}
/*URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
uriBuilder.addParameter("query", "花千骨");*/
HttpGet get = new HttpGet(uriBuilder.build());//生產一個httpget連接
//添加head, 用setheader 如果已經存在就重置, addheader如果已經存在進行新增同名的header
if(headers!=null&&headers.size()>0){
for (Map.Entry<String, String> temp : headers.entrySet() ) {
//循環map裏面的每一對鍵值對,然後獲取key和value即時想要的參數的 key和value
get.setHeader(temp.getKey(),temp.getValue());
}
}
//執行請求
response = httpClient.execute(get);
//取響應的結果
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = response.getEntity();
entityString = EntityUtils.toString(entity, "utf-8");
System.out.println(entityString);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(response !=null){
response.close();
}
if (httpClient!=null){
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return entityString;
}
/**
* 傳入的參數爲Json格式的的post請求實現方式
* @param baseUrl
* @param parameters
* @return
*/
public String post(String baseUrl,String parameters) {
//CloseableHttpClient 實現了HttpClient, Closeable兩個接口
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost postmethod = new HttpPost(baseUrl);
//創建一個uri對象
CloseableHttpResponse response = null;
long startTime = 0L;
long endTime = 0L;
int status = 0;
String bodyString = null;
logger.info("parameters:" + parameters);
if (postmethod != null ) {
try {
// 建立一個NameValuePair數組,用於存儲欲傳送的參數
postmethod.addHeader("Content-type","application/json; charset=utf-8");
postmethod.setHeader("Accept", "application/json");
if(parameters != null && !"".equals(parameters.trim())){
postmethod.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
}
startTime = System.currentTimeMillis();
response = httpClient.execute(postmethod);
endTime = System.currentTimeMillis();
int statusCode = response.getStatusLine().getStatusCode();
logger.info("statusCode:" + statusCode);
logger.info("調用API 花費時間(單位:毫秒):" + (endTime - startTime));
if (statusCode != HttpStatus.SC_OK) {
logger.error("Method failed:" + response.getStatusLine());
status = 1;
}
// Read the response body
bodyString = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// 網絡錯誤
status = 3;
} finally {
logger.info("調用接口狀態:" + status);
try {
if(response !=null){
response.close();
}
if (httpClient!=null){
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bodyString;
}
/**
* get帶參調用方式二
* @param url
* @param parametersList
* @return
*/
public String get2(String url ,List<NameValuePair> parametersList) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
InputStream is = null;
String entityString =null;
String baseUrl =url;
//String baseUrl = "http://localhost:8080/MyWebxTest/getCityByProvinceEname.do";
/*//封裝請求參數
List<NameValuePair> params = Lists.newArrayList();
params.add(new BasicNameValuePair("cityEname", "henan"));*/
String str = "";
try {
//轉換爲鍵值對
str = EntityUtils.toString(new UrlEncodedFormEntity(parametersList, Consts.UTF_8));
System.out.println(str);
//創建Get請求
HttpGet httpGet = new HttpGet(baseUrl+"?"+str);
//執行Get請求,
response = httpClient.execute(httpGet);
//得到響應體
HttpEntity entity= response.getEntity();
entityString = EntityUtils.toString(entity);
if(entity != null){
is = entity.getContent();
//轉換爲字節輸入流
BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
String body = null;
while((body=br.readLine()) != null){
System.out.println(body);
}
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
//關閉輸入流,釋放資源
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//消耗實體內容
if(response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//關閉相應 丟棄http連接
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return entityString;
}
}