使用HttpClients请求外部接口
@Test
public void test(){
try{
// 使用httpClient请求
// 请求路径
String url = "localhost:8080/user/info";
// 请求头
Map headerMap = new HashMap();
headerMap.put("Content-Type", "application/json;chartset=UTF-8");
// 请求体
Map body = new HashMap();
body.put("phone",phone);
String requstString = JSONObject.toJSONString(body);
HttpConfig httpConfig = HttpConfigUtil.getHttpConfigForJson(
headerMap, requstString,
url,
700, "UTF-8");
String result = com.aspire.mall.common.httpclient.HttpClientUtil.post(httpConfig);
System.out.println("查询用户信息接口返回result:"+result);
JSONObject jsonObject = JSON.parseObject(result);
JSONArray subPhoneInfoArray = jsonObject.getJSONObject("Body").getJSONArray("subphonelist");
for(int i = 0 ;i<subPhoneInfoArray.size();i++){
JSONObject subPhoneInfo = subPhoneInfoArray.getJSONObject(i);
subPhones.add(subPhoneInfo.getString("subphone"));
}
System.out.println("查询用户信息接口返回subPhones:"+ String.join(",",subPhones));
}catch (Exception e){
e.printStackTrace();
}
}
但是报缺少安全证书:unable to find valid certification path to requested target
用以下办法能够暂时解决:请求HTTPS接口提示缺少安全证书
但是切换环境证书需要重新生成,不是办法。
@Test
public void test(){
try{
String url = "localhost:8080/user/info";
// 请求体
Map body = new HashMap();
body.put("phone",phone);
String requstString = JSONObject.toJSONString(body);
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.add("content-type", "application/json;chartset=UTF-8");
// 请求
HttpEntity<String> requst = new HttpEntity<>(requstString, headers);
// 使用RestTemplate请求
RestTemplate restTemplateHttps = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
ResponseEntity<JSONObject> responseBody = restTemplateHttps.postForEntity(url, requst, JSONObject.class);
JSONObject httpBody = responseBody.getBody();
System.out.println("接口返回参数:"+httpBody);
List<String> subPhones = new ArrayList<>();
JSONArray subPhoneInfoArray = httpBody.getJSONObject("Body").getJSONArray("subphonelist");
for(int i = 0 ;i<subPhoneInfoArray.size();i++){
JSONObject subPhoneInfo = subPhoneInfoArray.getJSONObject(i);
subPhones.add(subPhoneInfo.getString("subphone"));
}
System.out.println("查询用户信息接口返回subPhones:"+ String.join(",",subPhones));
}catch (Exception e){
e.printStackTrace();
}
}
参考:
RestTemplate实现http和https方式的远程调用:https://blog.csdn.net/qq_40950903/article/details/108647457
RestTemplate 中设置 header 以及使用 HTTP 基本认证的方法:https://blog.csdn.net/HeatDeath/article/details/79449607