概要
如何调用入参为json格式数据的接口,如何接收入参为json格式数据的接口
如何调用入参为json格式数据的接口
public static String doPost(String url,String inputJson) throws Exception {
HttpPost post = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String result = "";
try {
if (inputJson != null) {
StringEntity s = new StringEntity(inputJson, "UTF-8");
s.setContentType("application/json");// 发送json数据需要设置contentType
post.setEntity(s);
}
CloseableHttpResponse res = client.execute(post);
log.info("CloseableHttpResponse---------------=" + res);
log.info("res.getStatusLine().getStatusCode()---------------="
+ res.getStatusLine().getStatusCode());
HttpEntity resEntity = res.getEntity();
result = EntityUtils.toString(res.getEntity(), "UTF-8");// 返回json格式:
res.close();
} catch (Exception e) {
log.info("返回结构(Exception):" + result);
if(e.getMessage().toLowerCase().contains("timeout")){
throw new Exception("连接超时!");
}
throw new RuntimeException(e);
} finally {
post.abort();// 释放连接(新增加)
client.close();
}
log.info("返回结构:" + result);
JSONObject outData = JSONObject.parseObject(result);
log.info("-->解析报文结束:{}", outData);
if(outData.getInteger("err") != 0){
throw new RuntimeException("调用接口:"+PrescriptionCode.getInstance(prescriptionUrlNo).getUrlName()+"报错,错误信息:"+outData.getString("errmsg"));
}
return outData.getString("data");
}
入参:
{
“member”: “1”
}
出参:
{
“err”: 0,
“errmsg”: “操作成功”,
“data”: {
“a”: “b”
}
}
如何接收入参为json格式数据的接口
public ResponseDTO getDiagnosisStatus(HttpServletRequest httpServletRequest) throws Exception {
String requestDto = getDataFromRequest(httpServletRequest);
// json串转换为实体对象
RequestDTO requestDTOtemp = JSONObject.parseObject(requestDto, RequestDTO.class);
//处理入参
//返回
ResponseDTO responseDTO = new ResponseDTO();
responseDTO.setErr(0);
responseDTO.setErrmsg("");
return response580DTO;
}
public static String getDataFromRequest(HttpServletRequest request) throws Exception{
Gson gson = new Gson();
String type = request.getContentType();
log.info("type: "+type);
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try{
reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line);
log.info("sb: "+sb);
}
} catch (IOException e){
e.printStackTrace();
} finally {
try{
if (null != reader){
reader.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
入参:
{
“member”: “1”
}
出参:
{
“err”: 0,
“errmsg”: “操作成功”,
}