我是Rxjava的新手。我想从第一个api调用的响应中捕获访问令牌(作为标头的一部分),然后将该访问令牌(作为标头)用于后续的api调用。
注意:在第一个api调用中,响应没有正文,仅返回标头。
我的网络接口:
public interface NetworkInterface {
@POST("https://appauth.treuspan/Login")
Observable<Response<Void>> getAuthDetails(
@Header("Content-Type") String contentType,
@Body AuthRequestDetails authRequestDetails
);
@POST("https://appauth.treuspan//storedetails")
Observable<StoreDetailsResponse> getStoreDetails(
@Header("Content-Type") String contentType,
@Header("Accept") String accept,
@Header("Authorization") String authorization,
@Body AuthRequestBody authRequestBody
);
}
我的可观察方法:
public Observable<Response<Void>> getAuthObservable() {
return NetworkClient.getRetrofit().create(NetworkInterface.class)
.getAuthDetails("application/x-www-form-urlencoded",
new AuthRequestDetails().getAuthRequestDetails())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Response<Void>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Response<Void> voidResponse) {
String access_token_received = voidResponse.headers().get("access_token");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
以上内容无法编译。它的编译说:
Incompatible type:
required: io.reactivex.Observable<retrofit2.Response<java.lang.Void>>
Found: void
如果我能够成功进行上述调用,则必须使用访问令牌作为后续调用中标头的一部分,如下所示:
public Observable<StoreDetailsResponse> getStoreDetailsObservable() {
return NetworkClient.getRetrofit().create(NetworkInterface.class)
.getStoreDetails("application/x-www-form-urlencoded",
"application/json",
"Bearer access_token_received",
new AuthRequestBody().getAuthRequestBody())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<StoreDetailsResponse>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(StoreDetailsResponse response) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
上面的代码也无法编译。它说:
Incompatible type:
required: io.reactivex.Observable<com.example.androidtest.model.StoreDetailsResponse>
Found: void
请提出我该如何实现。
答案 0 :(得分:1)
subscribe(...)将返回一个订阅 尝试编辑您的代码,使方法返回这样的订阅
private func convertDataWithCompletionHandler(_ data: Data, completionHandlerForConvertData: (_ result: AnyObject?, _ error: NSError?) -> Void) {
var parsedResult: AnyObject! = nil
do {
//class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
//Returns a Foundation object from given JSON data.
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject
} catch {
let userInfo = [NSLocalizedDescriptionKey : "Could not parse the data as JSON: '\(data)'"]
completionHandlerForConvertData(nil, NSError(domain: "convertDataWithCompletionHandler", code: 1, userInfo: userInfo))
}
completionHandlerForConvertData(parsedResult, nil)
}