본문 바로가기
Flutter/Flutter FAQ

Flutter 바디에 Json을 포함한 HTTP POST - 플러터/다트, HTTP POST with Json on Body - Flutter/Dart

by 베타코드 2023. 7. 19.
반응형

질문


다음은 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

본문 응답은 비어 있으며, 요청에 보낸 본문 때문일 것으로 생각됩니다. 값이 있는 중첩된 json 객체에 대해 도움을 받을 수 있는 사람이 있을까요??

POSTMAN의 스크린샷:


답변


이 작동합니다!

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';
  // body data
  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;
}
반응형

댓글