GET请求
1.Google浏览器开发者工具截图图示
2.General
- Request URL :为请求链接
- Status Code :为HTTP响应状态码
3.ResponseHeaders :响应头
4.Request Headers :请求头
- 留意请求头内无Content-Type
5.Query String Parameters :GET 请求参数
POST请求(正常表单提交)
1.其他同上
2.Request Headers :请求头
- 注意Content-Type:application/x-www-form-urlencoded,与其他POST方式做对比
3.Form Data :post传递的值
- 格式与GET请求一致
POST请求(AJAX未指定请求头RequestHeader)
1.其他同上
2.Request Headers :请求头
- 注意Content-Type:text/plain;charset=UTF-8
- 有些未带charset=UTF-8
3.Request Payload :post传递的值,Form Data不见了
- 另外格式也与GET请求一致
POST请求(JSON传递参数)
1.其他同上
2.Request Payload :传递的值
- 注意字符串格式为json,与上面3种方式都不同
结论
前面3种都与常规方式一样,主要是第4种方式
1. 模拟POST请求传递JSON参数(PHP)
<?php
$url = "http://www.111.com";
$post['vin'] = "12312435";
//$post参数需要json_encode
$json = _curl_post($url, json_encode($post));
//$json为返回值,示例为返回JSON字符串
$data = json_decode($json, true);
//告诉浏览器输出为json字符串
header("Content-Type:application/json; charset=UTF-8");
echo $data['d']['Data'];
function _curl_post($url, $post) {
if ($url) {
//告诉服务端提交的为JSON参数
$header[] = "Content-Type:application/json; charset=UTF-8";
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $header,
CURLOPT_POST => 1,
CURLOPT_ENCODING => 'gzip,deflate',
CURLOPT_POSTFIELDS => $post
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
?>
2.后端获取请求参数
前面Ajax发送代码(使用jQuery):
$.ajax({
url: '',
type: 'POST',
contentType: 'application/json; charset=utf-8', // 很重要
traditional: true,
data: JSON.stringify({your json object}), // {"name":"zhangsan", "age": 28}
success: function(res, status, xhr) {
// your code ....
}
});
服务端接收代码(java):
HttpServletRequest req = ...
try {
BufferedReader reader = req.getReader();
StringBuilder sb = new StringBuilder();
char[] buff = new char[1024];
int len = -1;
while((len = reader.read(buff)) != -1) {
sb.append(buff, 0, len);
}
reader.close();
// example
System.out.println( sb.toString() ); // {"name":"zhangsan", "age": 28}
} catch(IOException e) {
// error
}