身体上有Json的HTTP POST - Flutter/Dart

Clá*_*ida 22 post json dart flutter

这是我向API发出请求的代码:

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
  var body = jsonEncode({ 'data': { 'apikey': '12345678901234567890' } });

  print("Body: " + body);

  http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  ).then((http.Response response) {
    print("Response status: ${response.statusCode}");
    print("Response body: ${response.contentLength}");
    print(response.headers);
    print(response.request);

  });
  }
Run Code Online (Sandbox Code Playgroud)

我对请求的响应有一个问题,它假设有一个带json的主体,但是出了点问题,我认为是我在body请求上发送的json,因为它是一个嵌套的json对象,并且key的值是json对象.我很想知道如何解析json并插入到请求的正文中.

这是标题响应:

 {set-cookie: JSESSIONID=DA65FBCBA2796D173F8C8D78AD87F9AD;path=/testes2/;HttpOnly, last-modified: Thu, 10 May 2018 17:15:13 GMT, cache-control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0, date: Thu, 10 May 2018 17:15:13 GMT, content-length: 0, pragma: no-cache, content-type: text/html, server: Apache-Coyote/1.1, expires: Tue, 03 Jul 2001 06:00:00 GMT}
Run Code Online (Sandbox Code Playgroud)

这就是假设:

Server: Apache-Coyote/1.1
Expires: Tue, 03 Jul 2001 06:00:00 GMT
Last-Modified: Thu, 10 May 2018 17:17:07 GMT
Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Vary: Accept-Encoding
Set-Cookie: JSESSIONID=84813CC68E0E8EA6021CB0B4C2F245BC;path=/testes2/;HttpOnly
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Run Code Online (Sandbox Code Playgroud)

身体反应是空的,我认为它是因为我发送请求的身体,任何人都可以帮助我在嵌套的json对象的价值?

邮递员的屏幕截图:

Raj*_*dav 33

这可行!

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';

  Map data = {
    'apikey': '12345678901234567890'
  }
  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}
Run Code Online (Sandbox Code Playgroud)

  • 这不起作用。内容类型标头将最终为“text/plain; charset=utf-8” (4认同)
  • 我遇到了这个问题,还与服务器上允许 CORS 混合在一起。导致 XMLHttpRequest 错误 (3认同)
  • 我没有检查其他人的答案,但是这个答案很快对我有用!! (2认同)
  • 谢谢你的例子!这有记录在任何地方吗?我浪费了很多时间直到找到这个例子......:/ (2认同)

Ric*_*eap 24

好的,最后我们有答案......

您正在指定headers: {"Content-Type": "application/json"},设置内容类型.在引擎盖下,无论是封装http还是较低级别dart:io HttpClient都将其更改为application/json; charset=utf-8.但是,您的服务器Web应用程序显然不期望后缀.

为了证明这一点,我在Java中试用了两个版本

conn.setRequestProperty("content-type", "application/json; charset=utf-8"); // fails
conn.setRequestProperty("content-type", "application/json"); // works
Run Code Online (Sandbox Code Playgroud)

您是否可以联系Web应用程序所有者来解释他们的错误?我无法看到Dart添加后缀的位置,但我会稍后再看.

编辑 后来的调查表明,这是一个http包,虽然为你做了很多繁重的工作,但是添加了服务器不喜欢的后缀.如果您无法让他们修复服务器,那么您可以绕过httpdart:io HttpClient直接使用它.你最终会得到一些通常为你处理的样板文件http.

下面的工作示例:

import 'dart:convert';
import 'dart:io';
import 'dart:async';

main() async {
  String url =
      'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
  Map map = {
    'data': {'apikey': '12345678901234567890'},
  };

  print(await apiRequest(url, map));
}

Future<String> apiRequest(String url, Map jsonMap) async {
  HttpClient httpClient = new HttpClient();
  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();
  // todo - you should check the response.statusCode
  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}
Run Code Online (Sandbox Code Playgroud)

根据您的使用情况,重新使用HttpClient可能更有效,而不是为每个请求继续创建新的HttpClient.Todo - 添加一些错误处理;-)

  • @CláudioAlmeida使用较低级别的`HttpClient`用工作版本更新了答案。 (2认同)
  • 理查德·希普 非常感谢你,它工作得很好,再次花费了你的时间!它非常有效,我会尝试要求他们解决服务器上的字符集请求!你创造了我的一天,我被困在这里 3 天,我变得没有动力了!!tyvm (2认同)
  • 此解决方案不适用于 Flutter Web 应用程序 (2认同)

Kes*_*R.P 8

这也可以工作:

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

  sendRequest() async {

    Map data = {
       'apikey': '12345678901234567890'
    };

    var url = 'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
    http.post(url, body: data)
        .then((response) {
      print("Response status: ${response.statusCode}");
      print("Response body: ${response.body}");
    });  
  }
Run Code Online (Sandbox Code Playgroud)

  • 这不仅有效,而且还清楚地表明大多数时候您不需要对数据进行 json 编码,谢谢! (2认同)
  • 对我不起作用:状态不佳:无法设置内容类型为“application/json”的请求的正文字段。 (2认同)

Dha*_*dav 8

这对我有用

String body = json.encode(parameters);

http.Response response = await http.post(
  url: 'https://example.com',
  headers: {"Content-Type": "application/json"},
  body: body,
);
Run Code Online (Sandbox Code Playgroud)


Hưn*_*ịnh 7

我想很多人都对 Post'Content-type': 'application / json' 有问题这里的问题是将数据解析Map <String, dynamic>json

希望下面的代码可以帮助某人

模型:

class ConversationReq {
  String name = '';
  String description = '';
  String privacy = '';
  String type = '';
  String status = '';

  String role;
  List<String> members;
  String conversationType = '';

  ConversationReq({this.type, this.name, this.status, this.description, this.privacy, this.conversationType, this.role, this.members});

  Map<String, dynamic> toJson() {

    final Map<String, dynamic> data = new Map<String, dynamic>();

    data['name'] = this.name;
    data['description'] = this.description;
    data['privacy'] = this.privacy;
    data['type'] = this.type;

    data['conversations'] = [
      {
        "members": members,
        "conversationType": conversationType,
      }
    ];

    return data;
  }
}
Run Code Online (Sandbox Code Playgroud)

要求:

createNewConversation(ConversationReq param) async {
    HeaderRequestAuth headerAuth = await getAuthHeader();
    var headerRequest = headerAuth.toJson();
/*
{
            'Content-type': 'application/json',
            'x-credential-session-token': xSectionToken,
            'x-user-org-uuid': xOrg,
          }
*/

    var bodyValue = param.toJson();

    var bodydata = json.encode(bodyValue);// important
    print(bodydata);

    final response = await http.post(env.BASE_API_URL + "xxx", headers: headerRequest, body: bodydata);

    print(json.decode(response.body));
    if (response.statusCode == 200) {
      // TODO
    } else {
      // If that response was not OK, throw an error.
      throw Exception('Failed to load ConversationRepo');
    }
  }
Run Code Online (Sandbox Code Playgroud)


wil*_*ola 5

我是这样实现的:

static createUserWithEmail(String username, String email, String password) async{
    var url = 'http://www.yourbackend.com/'+ "users";
    var body = {
        'user' : {
          'username': username,
          'address': email,
          'password': password
       }
    };

    return http.post(
      url, 
      body: json.encode(body),
      headers: {
        "Content-Type": "application/json"
      },
      encoding: Encoding.getByName("utf-8")
    );
  }
Run Code Online (Sandbox Code Playgroud)