身体上有Json的HTTP POST-Flutter/Dart [英] HTTP POST with Json on Body - Flutter/Dart

查看:143
本文介绍了身体上有Json的HTTP POST-Flutter/Dart的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is my code to make a request to an 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);

  });
  }

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

I have a problem with the response from the request, where its suppose to have a body with json, but something went wrong and i think is with the json that i send on the body request, because it is a nested json object, and the value of the key is a json object. i would love to know how i can parse the json right and insert into body of the request.

这是标题响应:

 {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}

这就是应该的样子:

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

主体响应为空,我认为这是因为我在请求中发送的主体,有人可以帮助我处理嵌套json对象的值吗?

the body response came empty and i think its because the body i sent on the request, can anyone help me with the nested json object in value??

  • [1]: https://i.stack.imgur.com/JIbPz.png
  • [2]: https://i.stack.imgur.com/BFpLA.jpg

推荐答案

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

OK, finally we have an answer...

您正确地指定了headers: {"Content-Type": "application/json"},来设置您的内容类型.在引擎盖下,软件包http或较低级别的dart:io HttpClient都将其更改为application/json; charset=utf-8.但是,您的服务器Web应用程序显然不需要后缀.

You are correctly specifying headers: {"Content-Type": "application/json"}, to set your content type. Under the hood either the package http or the lower level dart:io HttpClient is changing this to application/json; charset=utf-8. However, your server web application obviously isn't expecting the suffix.

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

To prove this I tried it in Java, with the two versions

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

您可以联系Web应用程序所有者以解释其错误吗?我看不到Dart在哪里添加后缀,但是我稍后再看.

Are you able to contact the web application owner to explain their bug? I can't see where Dart is adding the suffix, but I'll look later.

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

EDIT Later investigation shows that it's the http package that, while doing a lot of the grunt work for you, is adding the suffix that your server dislikes. If you can't get them to fix the server then you can by-pass http and use the dart:io HttpClient directly. You end up with a bit of boilerplate which is normally handled for you by 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;
}

根据您的用例,重用HttpClient可能会更有效,而不是继续为每个请求创建一个新请求.待办事项-添加一些错误处理;-)

Depending on your use case, it may be more efficient to re-use the HttpClient, rather than keep creating a new one for each request. Todo - add some error handling ;-)

这篇关于身体上有Json的HTTP POST-Flutter/Dart的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆