// 解析response封装返回对象httpResult
HttpResult httpResult = null;
if (response.getEntity() != null) {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
} else {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
}
// 返回结果
return httpResult;
}
/**
* 不带参数的post请求
*
* @param url
* @return
* @throws Exception
*/
public HttpResult doPost(String url) throws Exception {
HttpResult httpResult = this.doPost(url, null);
return httpResult;
}
/**
* 带参数的Put请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
// 声明httpPost请求
HttpPut httpPut = new HttpPut(url);
// 判断map不为空
if (map != null) {
// 声明存放参数的List集合
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 遍历map,设置参数到list中
for (Map.Entry<String, Object> entry : map.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
// 创建form表单对象
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
// 把表单对象设置到httpPost中
httpPut.setEntity(formEntity);
}
// 使用HttpClient发起请求,返回response
CloseableHttpResponse response = this.httpClient.execute(httpPut);
// 解析response封装返回对象httpResult
HttpResult httpResult = null;
if (response.getEntity() != null) {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
} else {
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
}
// 返回结果
return httpResult;
}
/**
* 带参数的Delete请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doDelete(String url, Map<String, Object> map) throws Exception {
// 声明URIBuilder
URIBuilder uriBuilder = new URIBuilder(url);
// 判断参数map是否为非空
if (map != null) {
// 遍历参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
// 设置参数
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 2 创建httpGet对象,相当于设置url请求地址
HttpDelete httpDelete = new HttpDelete(uriBuilder.build());
// 3 使用HttpClient执行httpGet,相当于按回车,发起请求
CloseableHttpResponse response = this.httpClient.execute(httpDelete);