Flutter Dart HTTP标头不起作用。发送带有“标头”的请求。发生响应授权错误时,{“ CODE”:401,“ MESSAGE”:“未经授权”}

时间:2019-06-20 07:37:44

标签: http flutter http-headers

使用授权和其他标头向API发送请求,未经授权返回。似乎服务器在请求时未获取标头。我尝试了不同的方法来请求发送HTTP标头,但失败了。我尝试了Dio,HttpClient和Normal http请求都失败了。我在这件事上花了2天,仍然没有解决。来自邮递员,并且其他媒体请求也有效。

Map<String,String> reqHeaders = {
  'Content-type': 'application/json',
  'Accept': 'application/json',
  "Authorization": "xxxxx",
  "langapi": "en"
};
Future<MzResponseData> getHttp() async {
  var dio = Dio();
  dio.options.baseUrl = baseUrl;
  dio.options.headers = reqHeaders;
  dio.options.contentType = ContentType.parse("application/json");
  Response response = await dio.get("/uri/");
  print(response);
}

2 个答案:

答案 0 :(得分:3)

尝试一下。

final response = await dio.get(
      url,
      options: Options(
        headers: {
          'Authorization': 'Bearer $token',
        },
      )
    );

答案 1 :(得分:0)

Future<MzResponseData> getHttp() async {
  var dio = await Dio();
  dio.options.baseUrl = baseUrl;
    dio.options.headers = Options(headers: {'Authorization': 'Bearer $token'})//add your type of authentication
  dio.options.contentType = ContentType.parse("application/json");
  Response response = await dio.get("/uri/");
  print(response);
}