image.png
协议规定 POST 的数据必须放在消息主体(entity-body)中,但没有规定数据使用什么编码方式。
以登录为列:
image.png
一:
通过浏览器原生的form表单提交数据,默认以 application/x-www-form-urlencoded将数据编码为key1=val1&key2=val2 的形式,key 和 val 都进行了 URL 转码
<form action="/upload" enctype="multipart/form-data" method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
File: <input type="file" name="file">
<input type="submit">
</form>
通过ajax提交post数据,一般使用application/json将数据编码为{key1:val1,key2:val2}
postman模拟这两种情况:
(1.1)模拟form表单,指定默认的编码方式
image.png
(1.2)消息主体格式为key1=val1&key2=val2
image.png
(2.1)模拟ajax,指定json的编码方式
image.png
image.png
(2.2)消息主体格式为json
image.png
二:
请求头(headers)中的 Content-Type 字段的作用:
服务端可以根据该值判断消息主体数据的编码格式
(1)form表单请求会根据默认的编码格式,在生成http post请求时,将content-type设置为对应的值
(2)代码httpclient的请求中,根据api要求将请求数据编码为指定的格式,并且设置content-type
三:
通过httpClient发起post请求
new UrlEncodedFormEntity(parameters)将 List<NameValuePair>数据按照x-www-form-urlencoded编码
StringEntity(jsonString, Charset.forName("UTF-8"))将jsonString数据按照application/json编码
private static String postRequest(String loginUrl, List<NameValuePair> parameters) {
HttpPost httpPost = new HttpPost(loginUrl);
httpPost.setHeader("Accept", "application/json, text/plain, */*");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
uefe = new UrlEncodedFormEntity(parameters);
httpPost.setEntity(uefe);
response = httpClient.execute(httpPost);
}
public static String post(String url, String jsonString) throws Exception{
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
}