场景:A服务方法中调用B服务(跨域),方式为HttpPost。postman直接调用,查询B服务返回的数据如下:

实现步骤:
1、准备好B服务的URL,用org.apache.http.client的HttpClient方法,并设置header。
String url = seagull.getSupplierUrl();
HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type","application/json");//设置header
2、将参数塞入body中,传给对方,其中有个坑,参数转StringEntity时,一定要设置字符集UTF_8,否则会取默认的ISO80009
JSONObject json = new JSONObject();
json.put("supplierName", supplierName);
StringEntity stringEntity = new StringEntity(json.toJSONString(),UTF_8);
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
3、调用HttpClient.execute(httpPost),查询B服务,并返回结果。
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
StringBuilder strBuilder = new StringBuilder();
if (null != strBuilder ) {
InputStream inputStream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String temp = "";
while ((temp = br.readLine()) != null) {
String str = new String(temp.getBytes(), "utf-8");
strBuilder.append(str);
}
}
String strTemp = strBuilder.toString();
其中,httpClient、HttpPost、HttpResponse都用org.apache.http下的包,别用其他的。

在SpringBoot应用中,通过HttpPost进行跨域远程调用B服务时,需要设置HttpClient和HttpPost,确保请求头正确,并且在将参数转化为StringEntity时指定UTF-8字符集以避免编码问题。调用完成后,使用HttpResponse获取B服务的返回结果。务必使用org.apache.http包下的类来完成此操作。
2万+

被折叠的 条评论
为什么被折叠?



