Httpclient 发送 post 请求可以封装多格式的参数,这篇我们封装json格式的:
1、客户端代码如下:
/**
* 参数以json形式传送
* @param request
* @return
* @throws IOException
*/
public NmpResponse doPostJson(NmpRequest request) throws IOException {
logger.info("------------开始POST请求-nmpHttpClient-----------");
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
PostMethod postMethod = new PostMethod(NMP_ROOT_URL+request.getUrl());
postMethod = setHeaderAuthInfo(postMethod);
//添加请求参数
String jsonParams = request.getJsonParam();
System.out.println("推送参数:"+jsonParams);
postMethod.setRequestEntity(new StringRequestEntity(jsonParams,null,null));
NmpResponse response = new NmpResponse();
try {
logger.info("------------开始执行POST请求,url:{}------------",NMP_ROOT_URL+request.getUrl());
int statusCode = httpClient.executeMethod(postMethod);
logger.info("------------POST请求结束,code={}------------",statusCode);
if (statusCode == 200){
response.setRespBody(postMethod.getResponseBody());
response.setResponseStr(postMethod.getResponseBodyAsString());
response.setRespHeaders(postMethod.getRequestHeaders());
} else{
logger.error("请求出错code={}:{}" ,statusCode ,postMethod.getStatusLine());
}
} catch (IOException e){
logger.error("请求出错IOException:{}" ,e);
throw e;
} finally {
postMethod.releaseConnection();
logger.info("------------结束POST请求-nmpHttpClient-----------");
}
return response;
}
2、服务端接收代码:
@RequestMapping(value = "/download/getListData")
public Object queryPartitionList(@RequestBody PartitionVO partitionVO){
if(Objects.isNull(partitionVO) ||StringUtils.isEmpty(partitionVO.getLayName()) ||CollectionUtils.isEmpty(partitionVO.getParNameList())){
logger.error("Method:queryPartitionList 入参不能为空");
return new JSONObject();
}
if (StringUtils.isEmpty(partitionVO.getProductVersion())){
partitionVO.setProductVersion(Constant.ProductVersionLastest);
}
JSONObject jsonObject = new JSONObject();
//业务代码省略
return jsonObject;
}
3、服务端 partitionVO和客户端 jsonParams 数据里的参数一一对应。