实际上我想在我的项目中使用 dio(Dart 的 Http 客户端)来处理所有 http 请求,我查看了官方文档但无法申请。
使用来自 package:http/http.dart 的 http 客户端,它工作完美,但我想与 Dio 一起使用。任何人都可以检查并帮助我,为什么它不起作用。提前致谢!
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:thunder_mobile/models/login_modal.dart';
import 'package:thunder_mobile/utils/all_shared_preference_helper.dart';
import 'package:thunder_mobile/utils/http.dart';
import 'package:dio/dio.dart';
class ApiHelper {
// Dio _dio = new Dio();
var url = "http://5c9db1fd3be4e30014a7d3da.mockapi.io/";
final thunderBaseUrl = 'https://{domain}/api/v1/';
var headers = {'Content-Type': 'application/json'};
String token;
var sharedPref = new AllSharedPreferenceHelper();
var thunderHeaders = {
'content-type': 'application/json',
'x-requested-with': 'XMLHttpRequest',
};
var thunderImageHeaders = {
'content-type': 'multipart/form-data',
'x-requested-with': 'XMLHttpRequest',
};
final loginHeader = {'X-Requested-With': 'XMLHttpRequest'};
setApiHeader() {
sharedPref.getLoginData().then((res) {
LoginModel loginData = LoginModel.fromJson(json.decode(res));
if (loginData.accessToken != null) {
thunderHeaders['authorization'] = 'Bearer ' + loginData.accessToken;
token = loginData.accessToken;
}
});
}
// --------------------http BASED (Working Successfully)--------------------------------------
Future getThunderRequest(apiUrl) async {
await setApiHeader();
final http.Response response =
await http.get(thunderBaseUrl + apiUrl, headers: thunderHeaders);
return response;
}
Future postThunderRequest(apiUrl, body) async {
await setApiHeader();
final response = await http.post(thunderBaseUrl + apiUrl,
headers: thunderHeaders, body: json.encode(body.toJson()));
return response;
}
// ----------------------DIO API'S(not Working)------------------------------------
Future getDioRequest(apiUrl) async {
Dio dio = new Dio();
dio.interceptors
.add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
await setApiHeader();
options.headers["token"] = thunderHeaders;
return options;
}));
try {
Response response = await Dio().get('https://{domain}/api/v1/master');
print(response);
} catch (e) {
print(e);
}
}```
最佳答案
更新
dio = Dio();
dio.options.baseUrl = URL_API_PROD;
dio.interceptors.add(InterceptorsWrapper(
onRequest: (Options option) async{
//my function to recovery token
await getToken().then((result) {
token = result;
});
option.headers = {
"Authorization": "Bearer $token"
};
}
));
//here i use the dio instance on constuctor and call the get verb to get the data
Future<List<Children>> getChildren() async {
Response response = await dio.get('/v1/pessoa/alunosresponsavel');
//here I map the json from response to my model(children)
return (response.data['Dados'] as List).map((child)=> Children.fromJson(child)).toList();
}
获取 token .dart
import 'package:shared_preferences/shared_preferences.dart';
getToken() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
String getToken = preferences.getString("LastToken");
return getToken;
}
PS-> 依赖shared_preferences 是必要的
关于api - Dio(Dart 的 Http 客户端)获取请求不适用于拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57089525/
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc
我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur
在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList()Obt
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h
我正在尝试使用Ruby2.0.0和Rails4.0.0提供的API从imgur中提取图像。我已尝试按照Ruby2.0.0文档中列出的各种方式构建http请求,但均无济于事。代码如下:require'net/http'require'net/https'defimgurheaders={"Authorization"=>"Client-ID"+my_client_id}path="/3/gallery/image/#{img_id}.json"uri=URI("https://api.imgur.com"+path)request,data=Net::HTTP::Get.new(path
Rails中有没有一种方法可以提取与路由关联的HTTP动词?例如,给定这样的路线:将“users”匹配到:“users#show”,通过:[:get,:post]我能实现这样的目标吗?users_path.respond_to?(:get)(显然#respond_to不是正确的方法)我最接近的是通过执行以下操作,但它似乎并不令人满意。Rails.application.routes.routes.named_routes["users"].constraints[:request_method]#=>/^GET$/对于上下文,我有一个设置cookie然后执行redirect_to:ba
Rails相对较新。我正在尝试调用一个API,它应该向我返回一个唯一的URL。我的应用程序中捆绑了HTTParty。我已经创建了一个UniqueNumberController,并且我已经阅读了几个HTTParty指南,直到我想要什么,但也许我只是有点迷路,真的不知道该怎么做。基本上,我需要做的就是调用API,获取它返回的URL,然后将该URL插入到用户的数据库中。谁能给我指出正确的方向或与我分享一些代码? 最佳答案 假设API为JSON格式并返回如下数据:{"url":"http://example.com/unique-url"
我正在使用Heroku(heroku.com)来部署我的Rails应用程序,并且正在构建一个iPhone客户端来与之交互。我的目的是将手机的唯一设备标识符作为HTTPheader传递给应用程序以进行身份验证。当我在本地测试时,我的header通过得很好,但在Heroku上它似乎去掉了我的自定义header。我用ruby脚本验证:url=URI.parse('http://#{myapp}.heroku.com/')#url=URI.parse('http://localhost:3000/')req=Net::HTTP::Post.new(url.path)#boguspara