我的本地主机是:http://localhost:8585/api/getproducts我在我的ProductController中使用@Requestmapping(/ api / getproducts)来访问我的产品页面。
点击按钮,我需要在另一台主机上调用api: http://10.120.130.22:9292/我尝试在新的Controller中使用以下代码来调用主机:
@RequestMapping("Trainer/reStaff/")
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody response(@RequestParam("trainingId") final int trainingId, HttpServletRequest request)
throws ClientProtocolException, IOException {
String hostname="http://10.120.130.22:9292/";
CloseableHttpClient httpclient = HttpClients.custom().build();
CloseableHttpResponse response=null;
try{
String uri=hostname+"Trainer/reStaff/?trainingId="+trainingId;
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
response = httpclient.execute(httpPost);
String responseData = EntityUtils.toString(response.getEntity());
if(response.getStatusLine().getStatusCode()==200)
System.out.println(responseData+"\n");
else
System.out.println("Error :" + responseData+"\n");
}finally {
httpclient.close();
response.close();
}
但我收到错误:
类型状态报告
消息
说明请求的资源不可用。
如何从控制器中调用新主机?
答案 0 :(得分:0)
我明白这是如何运作的。我们需要通过服务层中的httpPost传递url:
HttpPost httpPost = new HttpPost(hostUri); JsonObject jsonResponse = null;
try {
String httpRequestBody = jsonRequestBuilder.build().toString();
logger.info("Request Body: " + httpRequestBody);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(httpRequestBody));
HttpResponse httpResponse = httpClient.execute(httpPost);
logger.debug("Response Status: " + httpResponse.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line;
StringBuffer httpResponseBody = new StringBuffer();
while ((line = reader.readLine()) != null) {
httpResponseBody.append(line);
}
logger.info("Response Body: " + httpResponseBody.toString());
JsonReader jsonReader = Json.createReader(new StringReader(httpResponseBody.toString()));
jsonResponse = jsonReader.readObject();
jsonReader.close();
} catch (Exception ex) {
logger.error("Error occurred while invoking POST on ep: " + hostUrl, ex);
} finally {
httpPost.releaseConnection();
}
logger.debug("Exiting");
return jsonResponse;