Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 如何在flatter中使用url编码的正文发出HTTP POST请求?_Dart_Flutter - Fatal编程技术网

Dart 如何在flatter中使用url编码的正文发出HTTP POST请求?

Dart 如何在flatter中使用url编码的正文发出HTTP POST请求?,dart,flutter,Dart,Flutter,我试图在flifter中发出一个post请求,内容类型为url编码。当我写body:json.encode(data)时,它编码为纯文本 如果我写body:data我会得到错误type'\u InternalLinkedHashMap'不是type cast中类型“String”的子类型 这是数据对象 var match = { "homeTeam": {"team": "Team A"}, "awayTeam": {"team": "Team B"} }; 还有我的要求 var re

我试图在flifter中发出一个post请求,内容类型为url编码。当我写
body:json.encode(data)
时,它编码为纯文本

如果我写
body:data
我会得到错误
type'\u InternalLinkedHashMap'不是type cast中类型“String”的子类型

这是数据对象

var match = {
  "homeTeam": {"team": "Team A"},
  "awayTeam": {"team": "Team B"}
};
还有我的要求

var response = await post(Uri.parse(url),
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: match,
    encoding: Encoding.getByName("utf-8"));

您需要添加三个附加步骤: 首先,需要将JSON映射转换为字符串(使用JSON.encode) 然后,如果希望将其作为application/x-www-form-urlencoded发送,则需要对其进行Uri编码。 最后,您需要给出您要发布的名称的参数

例如(注意,这是使用dart:io HttpClient,但基本上是相同的):

在电线上产生这个

name=doodle&color=blue&homeTeam=%7B%22team%22%3A%22team+A%22%7D&awayTeam=%7B%22team%22%3A%22team+B%22%7D

或者,这个

  Map<String, String> body = {
    'name': 'doodle',
    'color': 'blue',
    'teamJson': json.encode({
      'homeTeam': {'team': 'Team A'},
      'awayTeam': {'team': 'Team B'},
    }),
  };

  Response r = await post(
    url,
    body: body,
  );
映射体={
“名字”:“涂鸦”,
“颜色”:“蓝色”,
“teamJson”:json.encode({
'主队':{'team':'teama'},
“awayTeam”:{“团队”:“团队B”},
}),
};
回复r=等待发帖(
网址,
身体:身体,,
);
在电线上产生这个

name=doodle&color=blue&teamJson=%7B%22homeTeam%22%3A%7B%22team%22%3A%22team+A%22%7D%2C%22awayTeam%22%3A%7B%22team%22%3A%22team+B%22%7D%7D

包:http
客户端负责:对Uri.encodeQueryComponent进行编码,utf8编码(注意这是默认值,因此无需指定它)并在Content-length头中发送长度。您仍然必须进行json编码。

我想向您推荐这个包,它是一个功能强大的用于Dart/FLATT的Http客户端,支持拦截器、FormData、请求取消、文件下载、超时等

非常易于使用,在您的情况下,您可以:

Map<String, String> body = {
'name': 'doodle',
'color': 'blue',
'teamJson': {
  'homeTeam': {'team': 'Team A'},
  'awayTeam': {'team': 'Team B'},
  },
};

dio.post("/info",data:body, options: 
  new Options(contentType:ContentType.parse("application/x-www-form-urlencoded")))    
映射体={
“名字”:“涂鸦”,
“颜色”:“蓝色”,
“teamJson”:{
'主队':{'team':'teama'},
“awayTeam”:{“团队”:“团队B”},
},
};
dio.post(“/info”),数据:正文,选项:
新选项(contentType:contentType.parse(“application/x-www-form-urlencoded”))
可以自动对数据进行编码


更多详细信息请参阅。

您需要使用json.encode

榜样

var match = {
  "homeTeam": {"team": "Team A"},
  "awayTeam": {"team": "Team B"}
};
var response = await post(Uri.parse(url),
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: json.encode(match),
    encoding: Encoding.getByName("utf-8"));

我来这里只是想发出一个HTTP POST请求。以下是如何做到这一点的示例:

导入'dart:convert';
导入“包:http/http.dart”;
makePostRequest()异步{
final uri=uri.parse('http://httpbin.org/post');
最终标题={'Content-Type':'application/json'};
映射体={'id':21,'name':'bob'};
字符串jsonBody=json.encode(body);
最终编码=encoding.getByName('utf-8');
回复=等待发帖(
乌里,
标题:标题,
body:jsonBody,
编码:编码,
);
int statusCode=response.statusCode;
字符串responseBody=response.body;
}
另见


我是用dart的http包这样做的。不太花哨。我的端点不接受其他方法的参数,但它接受了这样的参数,参数中包含了括号

import 'package:http/http.dart' as http;

String url = "<URL>";

Map<String, String> match = {
  "homeTeam[team]": "Team A",
  "awayTeam[team]": "Team B",
};

Map<String, String> headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

http.post(url, body: body, headers: headers).then((response){
    print(response.toString());
});
import'package:http/http.dart'作为http;
字符串url=“”;
映射匹配={
“主队”:“A队”,
“awayTeam[团队]”:“B团队”,
};
映射头={
“内容类型”:“应用程序/x-www-form-urlencoded”
}
post(url,body:body,headers:headers){
打印(response.toString());
});
我建议使用这个库。它支持大量使用API的操作

最新的Dio版本。只需执行以下操作:

BaseOptions options = new BaseOptions(
baseUrl: "https://www.xx.com/api",
connectTimeout: 5000,
receiveTimeout: 3000,);
Dio dio = new Dio(options);
//
Map<String, String> params = Map();
params['username'] = '6388';
params['password'] = '123456';
//
response = await dio.post("/login", data: FormData.fromMap(params));
BaseOptions=newbaseoptions(
基本URL:“https://www.xx.com/api",
连接超时:5000,
接收超时:3000,);
Dio Dio=新的Dio(选项);
//
Map params=Map();
参数['username']='6388';
参数['password']='123456';
//
response=wait-dio.post(“/login”,数据:FormData.fromMap(params));
地图正文={
“getDetails”:“true”
};
最终响应=等待
http.post(“https://example.com/“,正文:正文);
如果(response.statusCode==200){
//你的代码
}
在“UserModel”位置写下您的模型名称,不要在正文中传递字符串。使用“Map”会产生问题,如下所示

static Future<UserModel> performUserLogin(String username, String password) async{
    
        try{
    
          Map<String, String> headers = {"Content-type": "application/json"};
          
    
          Map<String, String> JsonBody = {
            'username':  username,
            'password': password
          };
    
          print("The JSON Object is here $body");
          // make POST request
          final response = await http.post(loginAPIURL,body: JsonBody);
          // check the status code for the result
          int statusCode = response.statusCode;
          print("Login calling $response");
    
    
          if (statusCode == 200){
    
          
    
          }else{
            return null;
            //return UserModel();
            throw Exception("Error in login");
          }
    
        } catch (e) {
          throw Exception(e);
        }
      }
静态未来性能登录(字符串用户名、字符串密码)异步{
试一试{
映射头={“内容类型”:“应用程序/json”};
映射JsonBody={
“用户名”:用户名,
“密码”:密码
};
打印(“JSON对象在这里是$body”);
//发帖
最终响应=等待http.post(loginAPIURL,body:JsonBody);
//检查结果的状态代码
int statusCode=response.statusCode;
打印(“登录呼叫$response”);
如果(状态代码==200){
}否则{
返回null;
//返回UserModel();
抛出异常(“登录错误”);
}
}捕获(e){
抛出异常(e);
}
}
后编码URL请求

static Future generalRequest()异步{
映射头=新映射();
标题[“内容类型”]=“应用程序/x-www-form-urlencoded;字符集=UTF-8”;
风险值数据={
“数据1”:“数据1值”,
“数据2”:“值2”
};
var部分=[];
data.forEach((键,值){
add(“${Uri.encodeQueryComponent(key)}=”
“${Uri.encodeQueryComponent(value)}”);
});
var formData=parts.join('&');
打印(表格数据);
return wait http.post(“$baseUrl/oauth/token”,headers:headers,body:formData);
}


使用DIO的简单get请求:

    Future<dynamic> get(String uri, {
    Map<String, dynamic> queryParameters,
    Options options,
  }) async {
    try {
      var response = await _dio.get(
        uri,
        queryParameters: queryParameters,
        options: options,
      );
      return response.data;
    } on SocketException catch (e) {
      throw SocketException(e.toString());
    } on FormatException catch (_) {
      throw FormatException("Unable to process the data");
    } catch (e) {
      throw e;
    }
  }
Future get(字符串uri{
映射查询参数,
选项,
})异步的{
试一试{
var响应=等待_dio.get(
乌里,
查询参数:查询参数,
选项:选项,
);
返回响应数据;
}在
Map<String, String> body = {
  'getDetails': 'true'
};

final response = await 
http.post("https://example.com/", body: body);

if (response.statusCode == 200) {
//Your code
}
static Future<UserModel> performUserLogin(String username, String password) async{
    
        try{
    
          Map<String, String> headers = {"Content-type": "application/json"};
          
    
          Map<String, String> JsonBody = {
            'username':  username,
            'password': password
          };
    
          print("The JSON Object is here $body");
          // make POST request
          final response = await http.post(loginAPIURL,body: JsonBody);
          // check the status code for the result
          int statusCode = response.statusCode;
          print("Login calling $response");
    
    
          if (statusCode == 200){
    
          
    
          }else{
            return null;
            //return UserModel();
            throw Exception("Error in login");
          }
    
        } catch (e) {
          throw Exception(e);
        }
      }
 static Future<http.Response> genearalRequest() async {
  Map<String,String> headers = new Map();
  headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
 var data = {
    "data1": "datat1 value",
    "data2": "value2"
   };
var parts = [];
data.forEach((key, value) {
  parts.add('${Uri.encodeQueryComponent(key)}='
      '${Uri.encodeQueryComponent(value)}');
});
var formData = parts.join('&');

print(formData);
return await http.post('$baseUrl/oauth/token', headers: headers, body: formData);
    Future<dynamic> get(String uri, {
    Map<String, dynamic> queryParameters,
    Options options,
  }) async {
    try {
      var response = await _dio.get(
        uri,
        queryParameters: queryParameters,
        options: options,
      );
      return response.data;
    } on SocketException catch (e) {
      throw SocketException(e.toString());
    } on FormatException catch (_) {
      throw FormatException("Unable to process the data");
    } catch (e) {
      throw e;
    }
  }
Future<dynamic> post(
    String uri, {
    data,
    Map<String, dynamic> queryParameters,
    Options options,
  }) async {
    try {
      var response = await _dio.post(
        uri,
        data: data,
        queryParameters: queryParameters,
        options: options,
      );
      return response.data;
    } on FormatException catch (_) {
      throw FormatException("Unable to process the data");
    } catch (e) {
      throw e;
    }
  }