一,编写返回对象
public class HttpResult {
// 响应的状态码
private int code;
// 响应的响应体
private String body;
get/set…
}
二,封装HttpClient
package cn.xxxxxx.httpclient;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Nameva luePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameva luePair;
import org.apache.http.util.EntityUtils;
public class APIService {
private CloseableHttpClient httpClient;
public APIService() {
// 1 创建HttpClinet,相当于打开浏览器
this.httpClient = HttpClients.createDefault();
}
/**
* 带参数的get请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doGet(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请求地址
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 3 使用HttpClient执行httpGet,相当于按回车,发起请求
CloseableHttpResponse response = this.httpClient.execute(httpGet);
// 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
// 状态码
// response.getStatusLine().getStatusCode();
// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
// EntityUtils.toString(response.getEntity(), "UTF-8");
HttpResult httpResult = null;
// 解析数据封装HttpResult
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;
&nbs