前言
最近遇到一个需求对接外部系统,我们自己的系统发送请求,根据请求内容的不同调用不同的外部系统。举例:我们是做互联网医院的,根据医生开处方选择药店的不同,调用各药店自己的系统,返回结果
WebClient和RestTemplate
spring5引入了 WebClient
pom配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
文章对你的收货
- 可以学到对接外部系统的一些设计
- 构造需要的json
- java项目中HTTPPost请求外部系统或者调用url数据的三种格式
- 文章中的工具类代码可以直接复用
对接步骤
一般外部系统对接,都会给一份对接文档里面有接口url和请求数据以及返回结果的示例
- 先拿postman测试外部接口通不通(如图:外部系统文档中url和body)
- postman测通以后,项目中编写请求代码,并测试
- 把外部系统的返回结果,格式化成本系统的结果集
设计思路
低耦合:本系统的类和外部系统分开,如果业务发生变化,只需修改中间类的实现就可以了。
先学习下如何构造json,查看我的另一篇(会构造的忽略)
https://blog.csdn.net/zhanghengchao123/article/details/122372149
HttpPost请求数据的三种格式
外部系统的请求格式有四种:
- 第一种get请求
- 第二种post请求 json格式的
- 第三种post请求 form-data表单格式
- 第四种post请求 x-www-form-urlencoded格式
正好我对接的3个外部系统都有,下面看看这四种格式请求在代码中的实现
依赖
<!-- httpclient请求依赖 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.7</version>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
构造json示例(上面有另一篇博客地址有详细教程)
JSONObject jsonObject =new JSONObject();
String hisPrescriptionInifoVoStr = JSONObject.toJSONString(hisPrescriptionInifoVo);
JSONObject hisPrescriptionInifoVoJson = JSONObject.parseObject(hisPrescriptionInifoVoStr);
jsonObject.put("record",hisPrescriptionInifoVoJson);
String conditionListStr = JSONObject.toJSONString(conditionList);
JSONArray conditionListJsonArray = JSONObject.parseArray(conditionListStr);
jsonObject.put("conditionList",conditionListJsonArray);
String paymentVoListStr = JSONObject.toJSONString(paymentVoList);
JSONArray paymentVoListJsonArray = JSONObject.parseArray(paymentVoListStr);
jsonObject.put("paymentList",paymentVoListJsonArray);
正常的post请求json数据格式(如图)
代码:
//请求内容转换为 json数据字符串 (构造json字符串看上面示例)
String body= jsonObject.toString();
//创建一个http连接
CloseableHttpClient client = HttpClients.createDefault();
//创建Httppost请求
HttpPost httpPost = new HttpPost("http://175.33.10/hisApi/saveRecipeRecord?apiId=hh4444");
//添加头部
httpPost.addHeader("Content-Type", "application/json");
//请求内容格式化
httpPost.setEntity(new StringEntity(body, "utf-8"));
//结果返回response
CloseableHttpResponse response = null;
//请求流返回内容读取
BufferedReader reader = null;
//返回值格式化
StringBuffer responseString = null;
try {
//发起请求
response = client.execute(httpPost);
//判断识别码200说明请求连接成功
if (response.getStatusLine().getStatusCode() == 200) {
reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String inputLine;
responseString = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
responseString.append(inputLine);
}
}
} catch (Exception e) {
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//返回结果转换为字符串
String reultStr = responseString.toString();
//返回结果转换为json对象
JSONObject jsonObjectData = JSONObject.parseObject(reultStr);
//返回值判断根据接口文档判断按个值是成功的标志 ,再用本系统结果集包装类R包装返回值给本系统用
if(jsonObjectData.getString("success").contains("1")){
return R.ok();
}else{
return R.error(responseString.toString());
}
post请求form-data表单格式 如图:
代码请求思路: 这种表单格式的,把 表单的值都放到 url连接中,代码示例如下:
//请求内容转换为 json数据字符串 (构造json字符串看上面示例)
String body= jsonObject.toString();
//因为body有中文所以要 设置utf-8
String encode = URLEncoder.encode(body, "UTF-8");
CloseableHttpClient client = HttpClients.createDefault();
String tou="?client=4b9d92e8078967ae7069919793c45131&format=json&nonce=5×tamp=1153463&signature=woith234jhsehhsdf¬es="+encode;
HttpPost httpPost = new HttpPost("http://yyf.woxu.com:6566/order/import-template/upload-prescription"+tou);
httpPost.addHeader("Content-Type", "application/json");
//结果返回response
CloseableHttpResponse response = null;
//请求流返回内容读取
BufferedReader reader = null;
//返回值格式化
StringBuffer responseString = null;
try {
//发起请求
response = client.execute(httpPost);
//判断识别码200说明请求连接成功
if (response.getStatusLine().getStatusCode() == 200) {
reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String inputLine;
responseString = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
responseString.append(inputLine);
}
}
} catch (Exception e) {
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//返回结果转换为字符串
String reultStr = responseString.toString();
//返回结果转换为json对象
JSONObject jsonObjectData = JSONObject.parseObject(reultStr);
//返回值判断根据接口文档判断按个值是成功的标志 ,再用本系统结果集包装类R包装返回值给本系统用
if(jsonObjectData.getString("success").contains("1")){
return R.ok();
}else{
return R.error(responseString.toString());
}
post请求x-www-form-urlencoded 格式 如图:
代码:
//请求内容转换为 json数据字符串 (构造json字符串看上面示例)
String body= jsonObject.toString();
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(“url地址”);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
//============== 改造成 x-www-form-urlencoded 请求格式
SortedMap<String,String> sortedMap = null ;
sortedMap = new TreeMap<String,String>() ; //通过子类实例化接口对象
sortedMap.put("jsondhy", body);//body绑定到map上 key为jsondhy就是外部系统要求的key
//遍历map的值
List<NameValuePair> params = new ArrayList<>();
if (!sortedMap.isEmpty()) {
Set<Map.Entry<String, String>> entries = sortedMap.entrySet();
for (Map.Entry<String, String> parameter : entries) {
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(parameter.getKey(), parameter.getValue());
params.add(basicNameValuePair);
}
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//结果返回response
CloseableHttpResponse response = null;
//请求流返回内容读取
BufferedReader reader = null;
//返回值格式化
StringBuffer responseString = null;
try {
//发起请求
response = client.execute(httpPost);
//判断识别码200说明请求连接成功
if (response.getStatusLine().getStatusCode() == 200) {
reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String inputLine;
responseString = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
responseString.append(inputLine);
}
}
} catch (Exception e) {
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//返回结果转换为字符串
String reultStr = responseString.toString();
//返回结果转换为json对象
JSONObject jsonObjectData = JSONObject.parseObject(reultStr);
//返回值判断根据接口文档判断按个值是成功的标志 ,再用本系统结果集包装类R包装返回值给本系统用
if(jsonObjectData.getString("success").contains("1")){
return R.ok();
}else{
return R.error(responseString.toString());
}
get请求
get请求简单 把httppost换成httpget就可以了
HttpGet httpGet = new HttpGet(uri地址以及参数);