使用HTTP get请求发送JSON正文 [英] Send JSON body with HTTP get request

查看:83
本文介绍了使用HTTP get请求发送JSON正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JSON正文查询参数放入http.get请求中.我甚至尝试遵循此

这是我的代码混乱

  Future< List< Country>>fetchCountries(String name)异步{最终令牌= Provider.of< Auth>(上下文,监听:false).令牌;final params = {"name":"Uk"};尝试 {Uri uri = Uri.parse(APIPath.findCountry());最后的newUri = uri.replace(queryParameters:params);打印(newUri);//打印http://localhost:8080/country/find?name = uk最终响应=等待http.get(newUri,标头:[APIHeader.authorization(令牌),APIHeader.json()].reduce(mergeMaps));最终的jsonResponse = json.decode(response.body);如果(response.statusCode == 200){可迭代列表= jsonResponse ['result'];打印(列表);返回list.map((model)=> Country.fromJson(model)).toList();} 别的 {抛出HttpException(jsonResponse ["error"]));}} catch(错误){抛出错误;}} 

将正文放入http.get请求中并不像http.post请求那样起作用.知道我在做什么错吗?

解决方案

有几点需要牢记.

1)方法GET的HTTP RFC 说:

GET请求消息中的有效负载没有定义的语义...

在GET请求的主体中发送任何数据是一种糟糕的体系结构样式.

2)如果您想忽略它而仍然希望在GET请求中发送正文,则将内容类型标头设置为"application/json"是很有意义的.

3)您引用的示例未在GET请求中使用body.相反,它从给定的JSON对象检索参数值,并将其放入URL.然后,该URL将通过GET调用而没有正文.

我的建议

  • 如果URL参数的数量相对较少且其值较短,以使结果URL可读,请使用GET和带有参数的URL.
  • 如果带有参数的URL难以阅读,请将参数放在正文中并使用POST.
  • 没有精确的标准.这取决于您的口味和个人喜好.URL的可读性可能只是选择GET或POST时要考虑的标准之一.

I'm trying to put JSON body query parameters into http.get request. I tried to even follow this Flutter: Send JSON body for Http GET request but no luck there. No matter what I put into params variable I get all results from my backend. I have tested backend with postman and everything works fine

Here is my code in flutter

 Future<List<Country>> fetchCountries(String name) async {
    final token = Provider.of<Auth>(context, listen: false).token;
    final params = {"name": "Uk"};
    try {
      Uri uri = Uri.parse(APIPath.findCountry());
      final newUri = uri.replace(queryParameters: params);
      print(newUri); //prints http://localhost:8080/country/find?name=uk
      final response = await http.get(newUri,
          headers: [APIHeader.authorization(token), APIHeader.json()]
              .reduce(mergeMaps));
      final jsonResponse = json.decode(response.body);
      if (response.statusCode == 200) {
        Iterable list = jsonResponse['result'];
        print(list);
        return list.map((model) => Country.fromJson(model)).toList();
      } else {
        throw HttpException(jsonResponse["error"]);
      }
    } catch (error) {
      throw error;
    }
  }

Placing body into http.get request doesn't work as for http.post request. Any idea what am I doing wrong?

解决方案

There are several things to keep in mind.

1) The HTTP RFC for method GET says:

A payload within a GET request message has no defined semantics...

It is a bad architectural style, to send any data in the body of GET request.

2) If you want to ignore that and still want to send body in the GET request, it makes sense to set content type header to "application/json".

3) The example you referred does not use body in the GET request. Instead, it retrieves parameter values from the given JSON object and puts them to a URL. Then this URL is called via GET without body.

My suggestion:

  • If the number of URL parameters is relatively small and their values are short, so that the resulting URL is readable, use GET and URL with parameters.
  • If the URL with parameters becomes hard to read, put parameters to the body and use POST.
  • There are no precise criteria. It is a matter of your taste and your personal preferences. The readability of URL may be just one of criteria to consider when choosing GET or POST.

这篇关于使用HTTP get请求发送JSON正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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