当前位置: 首页 > 知识库问答 >
问题:

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

伍成仁
2023-03-14

这是我向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并插入到请求体中。

这是标头响应:

 {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

body响应为空,我想这是因为我在请求中发送了body,有人能帮我处理值中的嵌套json对象吗??

共有3个答案

方光华
2023-03-14

这也将起作用:

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}");
    });  
  }
伍胡媚
2023-03-14

好了,我们终于有了答案。。。

您正确地指定了标头:{"Content-Type":"Application/json"},来设置您的内容类型。在幕后,包超文本传输协议或较低级别的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

您是否能够联系web应用程序所有者解释他们的错误?我看不出Dart在哪里添加后缀,但我稍后会查看。

编辑稍后的调查表明,是超文本传输协议包在为您做大量繁琐工作的同时,添加了您的服务器不喜欢的后缀。如果您无法让他们修复服务器,那么您可以绕过超文本传输协议并直接使用dart: io HttpClient。您最终会得到一些样板文件,通常由超文本传输协议为您处理。

工作示例如下:

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可能比为每个请求创建一个新的更有效。Todo-添加一些错误处理;-)

章宏恺
2023-03-14

这工作!

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;
}
 类似资料:
  • 问题内容: 我已经在发送HTTP帖子的Objective-C中发送了方法,并且在正文中放置了一个字符串: 现在在Android中,我想做同样的事情,我正在寻找一种设置http帖子正文的方法。 问题答案: 您可以使用此代码段-

  • 在我们的部分应用程序中,我希望在中有一个简单的表单,就像下面的代码一样。不幸的是,当我把它放进去的时候,我得到了一个错误 在performLayout()期间抛出了以下断言:通常由TextField创建的InputDecorator不能具有无界宽度。当父小部件没有提供有限宽度约束时,就会发生这种情况。例如,如果InputDecorator包含在行中,则必须约束其宽度。可以使用扩展的小部件或Size

  • 问题内容: 我正在为应该获取数据的Android应用程序编写代码,将其打包为Json并将其发布到Web服务器,而该Web服务器又应该以json进行响应。 使用GET请求可以很好地工作,但是由于某种原因使用POST,所有数据似乎都被剥夺了,服务器什么也没收到。 这是一段代码: 我想我已经遵循了有关如何创建和发布参数的一般准则,但是显然没有。 在这一点上(在花了几个小时才意识到从未发送过任何帖子数据之

  • 顺便说一句,真的很好的谈话! 所有的输入都很感激!

  • 我正在我的flutter应用程序中实现一个DraggableScrollableSheet,并希望有一个粘性头,即只有列表视图滚动,工作表的顶部部分始终保持不变。我的小部件如下所示: 基本功能可以工作,但是,只有在拖动/滚动列表视图项时,工作表才是可拖动和可滚动的。我需要做什么更改来使列中的其他小部件也是可滚动的。我尝试了滚动和拖动小部件没有解决方案。 感谢任何帮助。

  • 问题内容: 我正在浏览此网站http://givemepass.blogspot.hk/2011/12/http- server.html 尝试使用android应用程序连接PHP服务器来获取消息。 GetServerMessage.java GetPhpServerMessageDemoActivity.java 我试图从该站点下载Android应用程序项目http://uploadingit.