Don*_* Ch 156 java post json servlets
我是HTTP POST到URL http:// laptop:8080/apollo/services/rpc?cmd = execute
使用POST数据
{ "jsondata" : "data" }
Run Code Online (Sandbox Code Playgroud)
Http请求的Content-Type为 application/json; charset=UTF-8
如何从HttpServletRequest获取POST数据(jsondata)?
如果我枚举请求参数,我只能看到一个参数,即"cmd",而不是POST数据.
Kde*_*per 263
Normaly你可以用同样的方式在servlet中获取和POST参数:
request.getParameter("cmd");
Run Code Online (Sandbox Code Playgroud)
但是,只有将POST数据编码为内容类型的键值对:"application/x-www-form-urlencoded",就像使用标准HTML表单一样.
如果对发布数据使用不同的编码模式,就像发布json数据流时的情况一样,则需要使用可以处理原始数据流的自定义解码器:
BufferedReader reader = request.getReader();
Run Code Online (Sandbox Code Playgroud)
Json后期处理示例(使用org.json包)
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
try {
JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
// Work with the data using methods like...
// int someInt = jsonObject.getInt("intParamName");
// String someString = jsonObject.getString("stringParamName");
// JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
// JSONArray arr = jsonObject.getJSONArray("arrayParamName");
// etc...
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*eaf -3
您是否从不同的来源(不同的端口或主机名)发帖?如果是这样,我刚刚回答的这个最近的主题可能会有所帮助。
问题在于 XHR 跨域策略,以及有关如何使用称为 JSONP 的技术来绕过它的有用提示。最大的缺点是 JSONP 不支持 POST 请求。
我知道在原来的帖子中没有提到 JavaScript,但是 JSON 通常用于 JavaScript,所以这就是我得出这个结论的原因
| 归档时间: |
|
| 查看次数: |
387921 次 |
| 最近记录: |