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

时间:2018-05-10 17:21:33

标签: json post dart flutter

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

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

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

这是标题响应:

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

这就是假设:

cellSelected

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

发布人的屏幕截图:

9 个答案:

答案 0 :(得分:13)

这行得通!

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

答案 1 :(得分:5)

这也可以:

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}");
    });  
  }

答案 2 :(得分:3)

我这样实现:

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")
    );
  }

答案 3 :(得分:2)

这对我有用

String body = json.encode(data);

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

答案 4 :(得分:1)

我认为很多人对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;
  }
}

请求:

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');
    }
  }

答案 5 :(得分:1)

就我而言,Flutter 应用程序中的 POST 可以在 Web 上运行,但不能在 Android 设备或模拟器上运行。

Flutter->服务器->API

为了修复它,我:

  1. 更改了服务器上的 HTTP HEADER:

    $curlArr[CURLOPT_HTTPHEADER] = str_replace("application/x-www-form-urlencoded; charset=utf-8",
      "application/x-www-form-urlencoded",$curlArr[CURLOPT_HTTPHEADER]);
    
  2. 从邮递员那里复制了大部分标题到我的应用程序。

答案 6 :(得分:0)

这是使用HTTPClient类的

 request.headers.add("body", json.encode(map));

我将编码后的json主体数据附加到标题并添加到其中。它对我有用。

答案 7 :(得分:0)

我忘记了启用

app.use(express.json());

在我的NodeJs服务器中。

答案 8 :(得分:0)

String body = json.encode(parameters);

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

这对我有用!