import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class HttpClientHelper {
// @Autowired
private CloseableHttpClient httpClient;
// @Autowired
private RequestConfig config;
/**
* 不帶參數的get請求,如果狀態碼爲200,則返回body,如果不爲200,則返回null
*
* @param url
* @return
* @throws Exception
*/
public String doGet(String url) throws Exception {
// 聲明 http get 請求
HttpGet httpGet = new HttpGet(url);
// 裝載配置信息
httpGet.setConfig(config);
// 發起請求
CloseableHttpResponse response = this.httpClient.execute(httpGet);
// 判斷狀態碼是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
// 返回響應體的內容
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
return null;
}
/**
* 帶參數的get請求,如果狀態碼爲200,則返回body,如果不爲200,則返回null
*
* @param url
* @return
* @throws Exception
*/
public String doGet(String url, Map<String, Object> map) throws Exception {
URIBuilder uriBuilder = new URIBuilder(url);
if (map != null) {
// 遍歷map,拼接請求參數
for (Map.Entry<String, Object> entry : map.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 調用不帶參數的get請求
return this.doGet(uriBuilder.build().toString());
}
/**
* 帶參數的post請求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
// 聲明httpPost請求
HttpPost httpPost = new HttpPost(url);
// 加入配置信息
httpPost.setConfig(config);
// 判斷map是否爲空,不爲空則進行遍歷,封裝from表單對象
if (map != null) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
// 構造from表單對象
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
// 把表單放到post裏
httpPost.setEntity(urlEncodedFormEntity);
}
// 發起請求
CloseableHttpResponse response = this.httpClient.execute(httpPost);
HttpResult httpResult =new HttpResult();
httpResult.setCode(response.getStatusLine().getStatusCode());
httpResult.setBody(EntityUtils.toString(
response.getEntity(), "UTF-8"));
return httpResult;
}
/**
* 不帶參數post請求
*
* @param url
* @return
* @throws Exception
*/
public HttpResult doPost(String url) throws Exception {
return this.doPost(url, null);
}
}
請求相關
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.