为何会出现远程接口本地调式没有任何问题,但是部署到服务器之后,有时候是正常,有时候是没有任何响应?
仅仅针对远程调用get请求。代码如下图所示:
RestTemplate restTemplate = new RestTemplate();
Map<String, Object> map = new HashMap<>();
// map.put("bm",bm);
//请求参数类型(JSON)
MediaType mediaType = MediaType.parseMediaType("application/json");
//定义请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
//接收所有类型请求
headers.add("Accept", MediaType.ALL_VALUE);
//给定义的请求头与参数定义一个新的headers
HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(map, headers);
// 执行请求
ResponseEntity<ReturnData> response = restTemplate.exchange(”http://192.168.0.206:8087“+ "/contract/main/pullToDompByBm?bm=" + bm, HttpMethod.GET, mapHttpEntity, ReturnData.class);
ReturnData returnData = response.getBody();
修改后的代码,上线部署后接口正常执行。麻烦知道原因的高手评论区回复一下谢谢。
public static String doGet(String url, Map<String, String> param) {
System.out.println("00000000认证开始领用");
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
//System.out.println("我的传送地址"+uri);
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
System.out.println("请求相应的数据" + response);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
return resultString;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}