SpringBoot中方法中用Http调用远程方法,Body传参
程序员文章站
2022-07-12 20:16:56
...
场景: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下的包,别用其他的。
上一篇: Python代码的人脸检测
下一篇: Http中的request