前言: 相信大家在刚开始接触接口定义与调用时遇到过接口接收不到请求参数的问题,本人也一样,使用springmvc去定义接口或调用第三方http接口时或多或少会搞混;下面咱们一起来整理下接口定义和请求参数格式的关系。
一、首先我们需要认识下http请求中的Content-Type,我们常用的有以下几种:
1、application/x-www-form-urlencoded; charset=UTF-8,浏览器的原生 form 表单,提交的数据按照 key1=val1&key2=val2 的方式进行编码,key和value都进行了URL转码。
2、multipart/form-data:使用表单上传文件时,必须设置 form 的 enctyped 属性。
3、application/json; charset=utf-8,请求参数是序列化后的json格式字符串,方便提交复杂结构的数据,特别适合RESTful 的接口。
二、注解@RequestParam(value=“id”)
1、常用来处理地址栏传参和表单提交的参数绑定,Content-Type为application/x-www-form-urlencoded编码的内容,提交方式GET、POST
2、如果用java发送http请求,需采用key、value传参方式发送数据,如下写法:
public static String post(HttpClient httpClient, String url, Map<String, String> params,
Map<String, String> headers) throws ClientProtocolException, IOException {
logger.info("Ready Post Request Url[{}]", url);
HttpPost post = new HttpPost(url);
setHttpHeaders(post, headers);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairList, Consts.UTF_8);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
if (null == response || response.getStatusLine() == null) {
logger.info("Post Request For Url[{}] is not ok. Response is null", url);
return null;
} else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
logger.info("Post Request For Url[{}] is not ok. Response Status Code is {}", url,
response.getStatusLine().getStatusCode());
return null;
}
return EntityUtils.toString(response.getEntity());
}
三、注解@RequestBody
1、一般用来接收json格式数据,后端直接定义好请求参数的bean,Content-Type为application/json; charset=utf-8,使用示例:
@RequestBody User user
请求参数:
{
"id": 1,
"userName": "bryant",
"password": "123456",
"name": "kobe",
"Date": "1990-02-27"
}
2、使用java发送请求代码示例:
public static String post(HttpClient httpClient, String url, String content, Map<String, String> headers)
throws ClientProtocolException, IOException {
logger.info("Ready Post Request Url[{}]", url);
url = url.replaceAll(" ", "%20");
HttpPost post = new HttpPost(url);
setHttpHeaders(post, headers);
StringEntity entity = new StringEntity(content, Constants.CHARSET_UTF8);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
if (null == response || response.getStatusLine() == null) {
logger.info("Post Request For Url[{}] is not ok. Response is null", url);
return null;
} else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
logger.info("Post Request For Url[{}] is not ok. Response Status Code is {}", url,
response.getStatusLine().getStatusCode());
return null;
}
return EntityUtils.toString(response.getEntity(), "utf-8");
}
public static void main(String[] args) throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("empId", "1");
map.put("empName", "测试用户");
map.put("empEmail", "test@qq.com");
Map<String, String> head = new HashMap<>();
// 一定要设置参数格式
head.put("Content-Type", "application/json;charset=UTF-8");
System.out.println(HttpCaller.post(HttpClients.createDefault(), "http://localhost:8080/user/add",
JsonUtil.toJson(map), head));
}
3、如果使用postman调试接口,需要设置传参方式为raw-JSON,如下图: