此处将为大家介绍关于处理flutterhttp请求添加application/json报错CannotsetthebodyfieldsofaRequestwithcontent-type“ap...的
此处将为大家介绍关于处理flutter http请求添加application/json报错Cannot set the body fields of a Request with content-type “ap...的详细内容,此外,我们还将为您介绍关于$.ajax中contentType: “application/json” 的用法、$.ajax中contentType: “application/json” 的用法详解、@RequestBody接收Content-type为application/x-www-form-urlencoded字符串乱码、aes加解密后续问题contentType不是application/json时候后台解析请求对象request的有用信息。
本文目录一览:- 处理flutter http请求添加application/json报错Cannot set the body fields of a Request with content-type “ap...
- $.ajax中contentType: “application/json” 的用法
- $.ajax中contentType: “application/json” 的用法详解
- @RequestBody接收Content-type为application/x-www-form-urlencoded字符串乱码
- aes加解密后续问题contentType不是application/json时候后台解析请求对象request
处理flutter http请求添加application/json报错Cannot set the body fields of a Request with content-type “ap...
在flutter中在http请求发送时设置"content-type": "application/json"会出现报错Cannot set the body fields of a Request with content-type “application/json”
请求如下:
final putResponse = await http.put(''http://192.168.201.21/user/modifyUser'',
body: putData,
headers: {"token": userBasicsInfo.userTokenResult,"content-type": "application/json"}
).then((response){
var backResult;
if(response.statusCode == 200){
Utf8Decoder utf8decoder = Utf8Decoder();
backResult = json.decode(utf8decoder.convert(response.bodyBytes));
}else{
print(''数据请求错误:${response.statusCode}'');
}
return backResult;
});
请求发送之后会出现如下报错
E/flutter ( 7295): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Bad state: Cannot set the body fields of a Request with content-type "application/json".
解决方法
通过jsonEncode处理要提交的参数
final putData = jsonEncode(params); // 处理提交参数
final putResponse = await http.put(''http://192.168.201.21/user/modifyUser'',
body: putData,
headers: {"token": userBasicsInfo.userTokenResult,"content-type": "application/json"}
).then((response){
var backResult;
if(response.statusCode == 200){
Utf8Decoder utf8decoder = Utf8Decoder();
backResult = json.decode(utf8decoder.convert(response.bodyBytes));
}else{
print(''数据请求错误:${response.statusCode}'');
}
return backResult;
});
处理之后再提交即可成功
注意:
[body]设置请求的正文。它可以是[String],[List]或[Map]。如果它是一个String,则使用[encoding]进行编码,并将其用作请求的主体。请求的内容类型将默认为“text / plain”。
如果[body]是List,它将用作请求正文的字节列表。
如果[body]是Map,则使用[encoding]将其编码为表单字段。请求的内容类型将设置为"application/x-www-form-urlencoded"
; 这不能被覆盖。[encoding]默认为[utf8]。
$.ajax中contentType: “application/json” 的用法
https://blog.csdn.net/calyxmelo/article/details/54969244
不使用contentType: “application/json”则data可以是对象 $.ajax({ url: actionurl,type: "POST",datType: "JSON",data: { id: nodeId },async: false,success: function () {} }); 1 2 3 4 5 6 7 8 使用contentType: “application/json”则data只能是json字符串 $.ajax({ url: actionurl,contentType: "application/json" data: "{‘id‘: " + nodeId +"}",success: function () {} });
//请求后端接口,获取数据function getRequestData(method,url,reqData,callBack){ $.ajax({ type : method,url : url,data : JSON.stringify(reqData),contentType:"application/json",dataType:‘json‘,success : function(result) { callBack(result); } });}
$.ajax中contentType: “application/json” 的用法详解
具体内容如下所示:
$.ajax({ type: httpMethod, cache:false, async:false, contentType: "application/json; charset=utf-8", dataType: "json",//返回值类型 url: path+url, data:jsonData, success: function(data){ var resultData = ''返回码=''+data.status+'',响应结果=''+data.message+'',耗时=''+data.tcost; layer.msg(resultData,{icon: 1}); }, error : function(xhr, ts, et) { layer.msg(''服务调用失败!'', {icon: 2}); } });
区分:
contentType: 发送信息至服务器时内容编码类型,简单说告诉服务器请求类型的数据
默认值: "application/x-www-form-urlencoded"
dataType:告诉服务器,我要想什么类型的数据,除了常见的json、XML,还可以指定 html、jsonp、script或者text
不使用contentType: “application/json”则data可以是对象
$.ajax({ url: actionurl, type: "POST", datType: "JSON", data: { id: nodeId }, async: false, success: function () {} });
使用contentType: “application/json”则data只能是json字符串
$.ajax({ url: actionurl, type: "POST", datType: "JSON", contentType: "application/json" data: "{''id'': " + nodeId +"}", async: false, success: function () {} });
总结
以上所述是小编给大家介绍的$.ajax中contentType: “application/json” 的用法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
- 跨域解决之JSONP和CORS的详细介绍
- JSON生成Form表单的方法示例
- 简单说说angular.json文件的使用
- JavaScript根据json生成html表格的示例代码
- MongoDB使用mongoexport和mongoimport命令,批量导出和导入JSON数据到同一张表的实例
- nodejs读取本地中文json文件出现乱码解决方法
- Go语言的JSON处理详解
- JavaScript JSON使用原理及注意事项
@RequestBody接收Content-type为application/x-www-form-urlencoded字符串乱码
当发送方发送请求content-type为application/x-www-form-urlencoded,后端采用@RequestBody String body接收字符串出现乱码时,应在方法体加入如下代码即可:
@RequestMapping(value = "/tradeResult")
public void tradeResult(@RequestBody String body) throws Exception {
body = URLDecoder.decode(body, StandardCharsets.UTF_8.name());
}
aes加解密后续问题contentType不是application/json时候后台解析请求对象request
一、post请求的三种content-type
1、application/x-www-form-urlencoded 主要用于如下:
1.1: 最常见的POST提交数据方式。
1.2:原生form默认的提交方式(可以使用enctype指定提交数据类型)。
1.3:jquery,zepto等默认post请求提交的方式。
2、multipart/form-data
使用表单上传文件时,必须指定表单的 enctype属性值为 multipart/form-data. 请求体被分割成多部分,每部分使用 --boundary分割;
3、application/json
在http请求中,ContentType都是默认的值 application/x-www-form-urlencoded, 这种编码格式的特点是:name/value值对,
每组之间使用&连接,而name与value之间是使用 = 连接,比如 key=xxx&name=111&password=123456; 键值对一般的情况下是没有什么问题的,
是很简单的json形式;对于一些复制的数据对象,对象里面再嵌套数组的话,建议使用application/json传递比较好,开发那边也会要求使用application/json。因为他们那边不使用application/json的话,使用默认的application/x-www-form-urlencoded传递的话,开发那边先要解析成如上那样的,然后再解析成json对象,如果对于比上面更复杂的json对象的话,那么他们那边是很解析的,所以直接json对象传递的话,对于他们来说更简单。通过json的形式将数据发送给服务器。json的形式的优点是它可以传递结构复杂的数据形式,比如对象里面嵌套数组这样的形式等。
所以,application/json是现在最常用的请求contentType;
二、当前端发生ajax请求进行aes加密后,后台的请求对象要进行封装,而contentType不是application/json时候,后台要额外再封装一个请求对象,进行解析,成json对象,post请求;
1、前端公共js封装ajax请求的地方,对参数处理进行修改:
var param;
if(GLOBAL_CONFIG.aesOpen==''1''){
var p=self.param||{};
if(self.contentType==''application/json''){
var rsaStr=FWRSAHelper.encrypt(self.param);
param=JSON.stringify({p:encrypt(rsaStr,GLOBAL_CONFIG.aecKey)});
}else{
var rsaStr=FWRSAHelper.encrypt(JSON.stringify(self.param));
param={p:encrypt(rsaStr,GLOBAL_CONFIG.aecKey)};
}
}else{
param=self.param;
}
2、后台请求过滤器java代码中修改:
WrapperedResponse wrapResponse = new WrapperedResponse((HttpServletResponse) response);
if("application/json".equals(contentType)){
WrapperedRequest wrapRequest = new WrapperedRequest((HttpServletRequest) request, rsaResult);
chain.doFilter(wrapRequest, wrapResponse);
}else{
JSONObject jsonObject=JSONObject.parseObject(rsaResult);
HashMap newParam=new HashMap();
Iterator<String> it = jsonObject.keySet().iterator();
while(it.hasNext()){
String key = it.next();
Object value = jsonObject.getString(key);
newParam.put(key,value);
}
ParameterRequestWrapper wrapRequest=new ParameterRequestWrapper(request,newParam);
chain.doFilter(wrapRequest, wrapResponse);
}
其中,原先的代码不动,在对参数解密之后,如果contentType不是application/json时候,要对参数再进行一次解析,再封装一个请求对象;
封装的新的请求对象类:
package com.xxx.common.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Enumeration;
import java.util.Map;
import java.util.Vector;
/**
* 该类用于改写request.getParameterNames里的值
* 使用方法:HashMap newParam=new HashMap(request.getParameterMap());
* ParameterRequestWrapper wrapRequest=new ParameterRequestWrapper(request,newParam);
* */
public class ParameterRequestWrapper extends HttpServletRequestWrapper {
private Map params;
public ParameterRequestWrapper(HttpServletRequest request, Map newParams) {
super(request);
this.params = newParams;
}
public Map getParameterMap() {
return params;
}
public Enumeration getParameterNames() {
Vector l = new Vector(params.keySet());
return l.elements();
}
public String[] getParameterValues(String name) {
Object v = params.get(name);
if (v == null) {
return null;
} else if (v instanceof String[]) {
return (String[]) v;
} else if (v instanceof String) {
return new String[] { (String) v };
} else {
return new String[] { v.toString() };
}
}
public String getParameter(String name) {
Object v = params.get(name);
if (v == null) {
return null;
} else if (v instanceof String[]) {
String[] strArr = (String[]) v;
if (strArr.length > 0) {
return strArr[0];
} else {
return null;
}
} else if (v instanceof String) {
return (String) v;
} else {
return v.toString();
}
}
}
今天关于处理flutter http请求添加application/json报错Cannot set the body fields of a Request with content-type “ap...的介绍到此结束,谢谢您的阅读,有关$.ajax中contentType: “application/json” 的用法、$.ajax中contentType: “application/json” 的用法详解、@RequestBody接收Content-type为application/x-www-form-urlencoded字符串乱码、aes加解密后续问题contentType不是application/json时候后台解析请求对象request等更多相关知识的信息可以在本站进行查询。
本文标签: