java HttpClient远程调用
// 开始远程调用接口===============================================
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
// 创建http POST请求
HttpPost httpPost = new HttpPost("http://127.0.0.1:1234/recommender/service/");
// 对JSONObject格式的数据进行转型
String string = jsonObject.toString();
StringEntity entity = new StringEntity(string, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
// 设置Post参数
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
CloseableHttpResponse response = null;
String content = null;
// 开始链接
try {
response = httpClient.execute(httpPost);
if (Objects.isNull(response)){
throw new ServiceException("调用接口返回数据出错");
}
System.out.println(response.getStatusLine());
// 判断调用状态
if(response.getStatusLine().getStatusCode() == 200){
// 获取返回结果
HttpEntity httpEntity = response.getEntity();
// 结果转型为String
content = EntityUtils.toString(httpEntity, "UTF-8");
if (Objects.isNull(content)){
throw new ServiceException("转型数据错误");
}
System.out.println(content);
}
}catch (Exception e) {
e.printStackTrace();
LOGGER.error("调用数据接口出错", e);
}finally {
if (response != null){
response.close();
}
}
// 链接关闭======================================================
httpClient.close();