- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我用它来配置我的改造:
RestAdapter restAdapter = new RestAdapter.Builder()
//add headers to requests
.setRequestInterceptor(getAuthenticatedRequestInterceptor())
.setEndpoint(BASE_URL)
.setConverter(new GsonConverter(getGson()))
.build();
并且 getAuthenticatedRequestInterceptor()
方法将 header 添加到请求中:
public AccountRequestInterceptor getAuthenticatedRequestInterceptor() {
AccountRequestInterceptor interceptor = new AccountRequestInterceptor();
Map<String, String> headers = new HashMap<>();
String accessToken = null;
try {
accessToken = TokenProvider.getInstance(mContext).getToken();
} catch (InterruptedException e) {
}
headers.put(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION + accessToken);
interceptor.setHeader(headers);
return interceptor;
}
getToken()
方法是:
private synchronized string getToken() throws InterruptedException {
if (!isRefreshing()) {
//This is very important to call notify() on the same object that we call wait();
final TokenProvider myInstance = this;
setRefreshing(true);
MyApplication.getRestClient().getAccountService().getRefreshedToken(mLoginData.getRefreshToken())
.subscribe(new Observer<LoginResponse>() {
@Override
public void onCompleted() {
synchronized (myInstance) {
setRefreshing(false);
myInstance.notifyAll();
}
}
@Override
public void onError(Throwable e) {
synchronized (myInstance) {
setRefreshing(false);
myInstance.notifyAll();
}
}
@Override
public void onNext(LoginResponse loginResponse) {
synchronized (myInstance) {
mLoginData = loginResponse;
mAccountProvider.saveLoginData(loginResponse);
myInstance.notifyAll();
}
}
});
}
this.wait();
return mLoginData.getToken();
}
TokenProvider.getInstance(mContext).getToken()
在主线程上有一个 wait()
来获取异步方法的响应,我知道这是一个不好的事情,但我需要在这里等待响应从中获取 token 然后返回 token 。我如何在单独的线程中执行此操作以避免在主线程上等待?
注意:
1 - 在任何带有改造的请求之前调用它。
2 - 我 read this我知道我可以在请求失败后刷新 token ,但出于商业原因,我想避免使用无效 token 。
3 - 我在我的 Activity
中调用 MyApplication.getRestClient().getAccountService().login(loginRequest,callback... )
并在添加 token 之前调用所有内容发生在后台线程中。所以我想使用我的 token 而不阻塞主线程。
更新:我将以下拦截器
添加到我的新 OkHttp 中:
public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
Request newRequest;
try {
Log.d("addHeader", "Before");
String token = TokenProvider.getInstance(mContext).getToken();
if (token != null) {
newRequest = request.newBuilder()
.addHeader("Bearer", token)
.build();
} else {
// I want to cancel the request or raise an exception to catch it in onError method
// of retrofit callback.
}
} catch (InterruptedException e) {
Log.d("addHeader", "Error");
e.printStackTrace();
return chain.proceed(request);
}
Log.d("addHeader", "after");
return chain.proceed(newRequest);
}
}
现在,如果 token 为空,我如何取消请求或引发异常以在改进回调的 onError 方法中捕获它?
最佳答案
这是一个有点奇怪的问题,但让我试着帮助你。 :)
如您所知,您可以在请求失败后使用响应拦截器进行改造来刷新 token 。
让我们尝试在请求之前使用拦截器。
public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// Here where we'll try to refresh token.
// with an retrofit call
// After we succeed we'll proceed our request
Response response = chain.proceed(request);
return response;
}
}
当你创建你的 api 时,创建一个新的 HttpClient:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new RequestTokenInterceptor());
然后将您的 http 客户端添加到您的适配器,如下所示:
.setClient(new OkClient(client))
如果这可行,在每次请求之前,您将首先尝试刷新 token ,然后继续您的 api 请求。所以在 ui 中与您的普通 api 调用没有区别。
编辑:
我也在编辑我的答案。如果您想在其他情况下返回错误,如果 token 为空,则您可以创建自定义响应:
private Response(Builder builder) {
this.request = builder.request;
this.protocol = builder.protocol;
this.code = builder.code;
this.message = builder.message;
this.handshake = builder.handshake;
this.headers = builder.headers.build();
this.body = builder.body;
this.networkResponse = builder.networkResponse;
this.cacheResponse = builder.cacheResponse;
this.priorResponse = builder.priorResponse;
}
或者您可以简单地返回一个空响应。如果您构建自定义响应并将代码设置为不为 200(例如 401 或 400+),您将在 Retrofit 的回调失败方法中收到该响应。比你可以做任何你想做的。
如果您返回 null,我认为您将得到一个 RuntimeException,并且您仍然可以在回调的失败方法中捕获响应。
在 else 中创建您自己的响应后,您可以创建自定义回调并捕获您的空响应并按照您想要的方式转换您的自定义错误,如下所示:
public abstract class DefaultRequestCallback<T> implements Callback<T> {
public abstract void failure(YourCustomException ex);
public abstract void success(T responseBean);
@Override
public void success(T baseResponseBean, Response response) {
if (response == null) {
// Here we catch null response and transform it to our custom Exception
failure(new YourCustomException());
}
} else {
success(baseResponseBean);
}
}
@Override
public void failure(RetrofitError error) {
// Here's your failure method.
// Also you can transform default retrofit errors to your customerrors
YourCustomException ex = new YourCustomException();
failure(ex);
}
}
我想这对你有帮助。
编辑 2:
您可以像下面这样构建一个新的 Response。 Retrofit 的 Response 类中有一个构建器模式。您可以从那里查看。
Response response = new Response.Builder().setCode(401).setMessage("Error Message").build();
关于java - 使用改造向请求添加 header 时如何避免在主线程上等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32175717/
我在让“@header”或任何其他@规则在ANTLR中工作时遇到麻烦。具有非常基本的语法,如下所示: grammar test; options { language = CSharp2;
我对来源和寄宿有疑问 我有一个ajax页面“Page A”,它将称为ajax提要“Page B” 我看到来自ajax调用的“页面B”的请求 header 具有源“http://mydomain.com
我在 pandas 中使用了数据透视表并获得了所需的数据框格式,但现在我有两行标题。数据透视表后的结果数据框如下: scenario Actual Plan
我在 pandas 中使用了数据透视表并获得了所需的数据框格式,但现在我有两行标题。数据透视表后的结果数据框如下: scenario Actual Plan
我想在主机将它们发送到网络之前修改数据包头(IP 头、TCP 头)。 例如,如果我使用 firefox 进行浏览,那么我想拦截所有来自 firefox 的数据包并修改 IP/TCP header ,然
我的 header 内容被包装到#header 中,但是当我设置边框显示结构时,它显示我的#header 的内容出现在#header 本身之后。可能是什么问题?这是我的代码: #header { bo
我是一名 Web 开发人员,使用过 PHP 和 .NET。有一年多的 Web 工作经验,我一直无法彻底了解浏览器缓存功能,希望这里的 Web Gurus 可以帮助我。我心中的问题是: 浏览器实际上是如
伙计们,我有一个问题,我不知道如何在一个 header 中连接多个 header ,我们称它为“主 header ”并使用该 header 中的函数,例如 // A.h #include class
我有一个包含 SOAP 消息的 XMLHTTPRequest。 我想添加用于标识消息并将由 C# Web 服务使用的 guid。 GUID 的目标是识别特定用户,并应护送所有用户请求以在服务器上进行身
我一直在阅读粘性标题,这是我目前所发现的。第一个粘性 header 效果很好,但是当它遇到第一个 header 时,我如何向上滚动第一个 header 并使第二个 header 卡住? http://
我想将当前基于 TableView 的数据网格转换为新的 UICollectionView 类。 这就是我当前的网格的样子: 我的网格有两个标题: 年份(2006a、2007a 等)和 类型(“收入”
我目前正在使用 Apollo 服务器。我正在尝试在响应 header 中设置一个属性。并且此属性是从客户端 graphQL 请求 header 中检索的。 我在网上查了一下。并看到了诸如使用插件或扩展
我的 Controller 的方法需要设置一个标题,例如X-Authorization .创建新对象( store Action )后,我执行转发以显示新创建的对象( show Action ): $
我正在研究一些关于 VLAN 的事情,发现了 VLAN 标签 和 header 。 如果我们有标准 802.3 以太网帧 的 MTU(1518 字节), header 802.3 中包含什么? 另外,
我是放心和 Java 的新手,我正在尝试做一个非常基本的测试来检查 API 的响应是否为 200 ok。 谁能告诉我我需要在下面的脚本中更改什么才能传递多个 header Id、Key 和 ConId
在我的项目中,我需要知道 zlib header 是什么样的。我听说它相当简单,但我找不到 zlib header 的任何描述。 例如,它是否包含魔数(Magic Number)? 最佳答案 zlib
我正在使用 JMeter 测试 HTTP 服务器,该服务器接受并验证 APIKey 并在成功时返回一个有时限的 token 。如果我有 token ,我想发送一个 token ;如果没有,我想发送一个
以太网 header 是什么样的? 是吗: 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|
我们的应用程序支持 CORS 配置 header 。我在两个不同的主机上分别配置了 testApp。两种设置都相互独立工作。host1 上的应用程序配置有 CORS header Access-Con
tlhelp32.h 不包含 windows.h 本身是有原因的吗?我一直在与大量的编译器错误作斗争,因为我在包含 tlhelp32.h 之后包含了 windows.h。这是设计决定还是出于什么原因?
我是一名优秀的程序员,十分优秀!