创建响应格式类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class HttpResult {
private int code;
private String body;
}
创建一个HttpClient工具类
public class HttpClientUtil {
private CloseableHttpClient httpClient;
public HttpClientUtil() {
// 1 创建HttpClinet,相当于打开浏览器
httpClient = HttpClients.createDefault();
}
}
创建GET请求方法
public HttpResult doGet(String url, Map<String, String> SignMap,String token, Map<String, String> map) throws Exception {
// 声明URIBuilder
URIBuilder uriBuilder = new URIBuilder(url);
// 判断参数map是否为非空
if (map != null) {
// 遍历参数
for (Map.Entry<String, String> entry : map.entrySet()) {
// 设置参数 将需要的参数添加到url
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 2 创建httpGet对象,相当于设置url请求地址
HttpGet httpGet = new HttpGet(uriBuilder.build());
//获取签名
//将业务参数构建成map后传入,得到nonce ,accesskey,timestamp,sign 请求头参数map
Map<String, String> map1 = SignUtil.buildSignParam (SignMap, Constant.clientId, Constant.clientSecret , 10 ,"GET");
//遍历存值
for(Map.Entry<String, String> entry : map1.entrySet()) {
httpGet.addHeader(entry.getKey(),entry.getValue());
}
//Authorization令牌
httpGet.addHeader("Authorization", "Bearer" + " " + token);
//Content-Type 数据结构
httpGet.addHeader("Content-Type", "application/json");
// 3 使用HttpClient执行httpGet,相当于按回车,发起请求
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
} catch (IOException e) {
HttpResult httpResult = new HttpResult();
httpResult.setCode(404);
httpResult.setBody("请求失败");
return httpResult;
}
// 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
// 状态码
// response.getStatusLine().getStatusCode();
// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
// EntityUtils.toString(response.getEntity(), "UTF-8");
HttpResult httpResult = new HttpResult();
// 解析数据封装HttpResult
if (response.getEntity() != null) {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
httpResult.setCode(response.getStatusLine().getStatusCode());
httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));
} else {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
httpResult.setCode(response.getStatusLine().getStatusCode());
//httpResult.setBody("");
}
System.out.println(httpResult.getBody());
// 返回
return httpResult;
}
因为这边调用的是题库的API接口,需要有相应的开发者id来生成需要的签名
创建POST方法
public HttpResult doPost(String url, String SignJson, String token, String jsonObj ) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
// 判断map不为空
if (jsonObj != null) {
//传入json字符串类型的参数
//map类型使用 formEntity
StringEntity stringEntity = new StringEntity(jsonObj,"UTF-8");
// 把表单对象设置到httpPost中
httpPost.setEntity(stringEntity);
System.out.println(stringEntity);
}
//将业务参数构建成map后传入,得到nonce ,accesskey,timestamp,sign 请求头参数map
Map<String, String> Headmap = SignUtil.buildSignParam (SignJson, Constant.clientId, Constant.clientSecret , 10 ,"POST");
//遍历存值
for(Map.Entry<String, String> entry : Headmap.entrySet()) {
httpPost.addHeader(entry.getKey(),entry.getValue());
}
//Authorization令牌
httpPost.addHeader("Authorization", "Bearer" + " " + token );
//Content-Type 数据结构
httpPost.addHeader("Content-Type", "application/json");
// 使用HttpClient发起请求,返回response
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (IOException e) {
HttpResult httpResult = new HttpResult();
httpResult.setCode(404);
httpResult.setBody("请求失败");
return httpResult;
}
// 解析response封装返回对象httpResult
HttpResult httpResult = new HttpResult();
// 解析数据封装HttpResult
if (response.getEntity() != null) {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),"UTF-8"));
httpResult.setCode(response.getStatusLine().getStatusCode());
httpResult.setBody(EntityUtils.toString(response.getEntity(),"UTF-8"));
} else {
//httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
httpResult.setCode(response.getStatusLine().getStatusCode());
httpResult.setBody("");
}
System.out.println(httpResult.getBody());
// 返回结果
return httpResult;
}
编写测试GetDemo
HttpClientUtil clientUtil = new HttpClientUtil();
// GET 查询学科接口
String geturl = "http://api.jtyedu.com/v1/api/subjects";
Map<String, String> temp = new HashMap<>();
// 添加学段参数
temp.put("stageId", "2");
//获取token
String token = getToken();
clientUtil.doGet(geturl,temp,token,temp);
输出结果
{"code":1,"msg":"成功","data":[{"id":1,"name":"语文"},{"id":2,"name":"数学"},{"id":3,"name":"英语"},{"id":4,"name":"道德与法治"},{"id":5,"name":"科学"},{"id":6,"name":"信息技术"},{"id":7,"name":"音乐"},{"id":8,"name":"美术"}]}
编写测试PostDemo
HttpClientUtil clientUtil = new HttpClientUtil();
String url = "http://api.jtyedu.com/v1/api/question/ids";
JSONObject jsonObject = new JSONObject();
jsonObject.put("questionIds", "1");
jsonObject.put("textbookId", "1");
String JsonString = jsonObject.toString();
clientUtil.doPost(url,JsonString,token,JsonString);
输出结果
{"code":1,"msg":"成功","data":[]}