- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
自从我集成了 RxJava2,我在所有返回 Observable 的改造调用中收到 401 unauthenticated 错误,我正在使用基本身份验证,我知道错误是由于它引起的,但为什么会这样适用于调试但不适用于发布。
在我看来,retrofit2 的 rxjava 适配器配置有问题
com.jakewharton.retrofit2.adapter.rxjava2.HttpException: HTTP 401 Unauthorized
01-22 19:24:14.872 11502-11502/? W/System.err: at com.jakewharton.retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(BodyObservable.java:54)
01-22 19:24:14.872 11502-11502/? W/System.err: at com.jakewharton.retrofit2.adapter.rxjava2.BodyObservable$BodyObserver.onNext(BodyObservable.java:37)
01-22 19:24:14.872 11502-11502/? W/System.err: at com.jakewharton.retrofit2.adapter.rxjava2.CallObservable.subscribeActual(CallObservable.java:43)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.Observable.subscribe(Observable.java:10514)
01-22 19:24:14.872 11502-11502/? W/System.err: at com.jakewharton.retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.Observable.subscribe(Observable.java:10514)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.internal.operators.observable.ObservableDoOnLifecycle.subscribeActual(ObservableDoOnLifecycle.java:33)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.Observable.subscribe(Observable.java:10514)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.internal.operators.observable.ObservableDoOnEach.subscribeActual(ObservableDoOnEach.java:42)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.Observable.subscribe(Observable.java:10514)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.internal.operators.observable.ObservableObserveOn.subscribeActual(ObservableObserveOn.java:44)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.Observable.subscribe(Observable.java:10514)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.internal.operators.observable.ObservableSubscribeOn$1.run(ObservableSubscribeOn.java:39)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.Scheduler$1.run(Scheduler.java:134)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:59)
01-22 19:24:14.872 11502-11502/? W/System.err: at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:51)
01-22 19:24:14.872 11502-11502/? W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-22 19:24:14.872 11502-11502/? W/System.err: at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
01-22 19:24:14.872 11502-11502/? W/System.err: at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
01-22 19:24:14.872 11502-11502/? W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1115)
01-22 19:24:14.872 11502-11502/? W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:590)
01-22 19:24:14.872 11502-11502/? W/System.err: at java.lang.Thread.run(Thread.java:818)
::project::
apply plugin: 'com.android.application' //or apply plugin: 'java'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'com.jakewharton.hugo'
apply plugin: 'android-apt'
def AAVersion = '4.1.0'
android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
defaultConfig {
applicationId "com.jutt.example1"
minSdkVersion 14
targetSdkVersion 25
versionCode 4
versionName "1.0"
multiDexEnabled false
}
buildTypes {
release {
minifyEnabled true
shrinkResources false
zipAlignEnabled true
//debuggable false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
}
apt {
arguments {
// you should set your package name here if you are using different application IDs
// resourcePackageName "your.package.name"
// You can set optional annotation processing options here, like these commented options:
// logLevel 'INFO'
// logFile '/var/log/aa.log'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
// Retrofit & OkHttp
// Because RxAndroid releases are few and far between, it is recommended you also
// explicitly depend on RxJava's latest version for bug fixes and new features.
// If you want to bind to Android-specific lifecycles
// If you want pre-written Activities and Fragments you can subclass as providers
compile 'com.android.support:support-v4:25.1.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
//compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.afollestad.material-dialogs:core:0.9.0.2'
compile 'com.github.ganfra:material-spinner:1.1.1'
compile 'com.android.support:design:25.1.0'
compile 'org.apache.commons:commons-lang3:3.4'
compile 'com.wdullaer:materialdatetimepicker:2.5.0'
//compile 'io.reactivex:rxandroid:1.2.1'
//compile 'io.reactivex:rxjava:1.1.6'
compile 'io.reactivex.rxjava2:rxjava:2.0.2'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.trello.rxlifecycle2:rxlifecycle:2.0.1'
}
::app::
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0-beta2'
classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'
classpath 'me.tatarka:gradle-retrolambda:3.3.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
// replace with the current version of the android-apt plugin
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
mavenLocal()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/zulqurnainjutt/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
-optimizationpasses 5
#-allowaccessmodification
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
#your package path where your gson models are stored
-keep class com.jutt.example1.model.** { *; }
# Retrofit, OkHttp, Gson
-keepattributes *Annotation*
-keepattributes Signature
-keep class com.squareup.okhttp.** { *; }
-keep interface com.squareup.okhttp.** { *; }
-dontwarn com.squareup.okhttp.**
-dontwarn rx.**
-dontwarn retrofit.**
-keep class retrofit.** { *; }
-keepclasseswithmembers class * {
@retrofit.http.* <methods>;
}
-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
# OkHttp3
-keepattributes Signature
-keepattributes *Annotation*
-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
# Rxjava-promises
-keep class com.darylteo.rx.** { *; }
-dontwarn com.darylteo.rx.**
# RxJava 0.21
-keep class rx.schedulers.Schedulers {
public static <methods>;
}
-keep class rx.schedulers.ImmediateScheduler {
public <methods>;
}
-keep class rx.schedulers.TestScheduler {
public <methods>;
}
-keep class rx.schedulers.Schedulers {
public static ** test();
}
## Retrolambda specific rules ##
# as per official recommendation: https://github.com/evant/gradle-retrolambda#proguard
-dontwarn java.lang.invoke.*
-keep class rx.internal.util.unsafe.** {
*;
}
错误所在的基本认证码:
class Factory {
private static SERVERAPI service;
public static SERVERAPI getIstance(Context context, String base_url,String username,String password) {
if (service == null) {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.readTimeout(2, TimeUnit.MINUTES);
builder.connectTimeout(2, TimeUnit.MINUTES);
builder.writeTimeout(2, TimeUnit.MINUTES);
//builder.certificatePinner(new CertificatePinner.Builder().add("*.androidadvance.com", "sha256/RqzElicVPA6LkKm9HblOvNOUqWmD+4zNXcRb+WjcaAE=")
// .add("*.xxxxxx.com", "sha256/8Rw90Ej3Ttt8RRkrg+WYDS9n7IS03bk5bjP/UXPtaY8=")
// .add("*.xxxxxxx.com", "sha256/Ko8tivDrEjiY90yGasP6ZpBU4jwXvHqVvQI0GS3GNdA=")
// .add("*.xxxxxxx.com", "sha256/VjLZe/p3W/PJnd6lL8JVNBCGQBZynFLdZSTIqcO0SJ8=")
// .build());
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
builder.addInterceptor(interceptor);
if(username != null) {
if(password == null){
password = "";
}
final String credential = Credentials.basic(username, password);
builder.addInterceptor(chain -> {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", credential);
requestBuilder.header("Accept", "application/json");
requestBuilder.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
});
}
}
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(context.getCacheDir(), cacheSize);
builder.cache(cache);
Retrofit retrofit;
//RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
if (base_url == null) {
retrofit = new Retrofit.Builder()
.client(builder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL).build();
} else {
retrofit = new Retrofit.Builder()
.client(builder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(base_url).build();
}
service = retrofit.create(SERVERAPI.class);
return service;
} else {
return service;
}
}
public static SERVERAPI getIstance(Context context) {
return getIstance(context, null,null,null);
}
public static SERVERAPI getInstanceWithAuthBasic(Context context,String username,String password){ // im using this method
return getIstance(context, null,username,password);
}
public static SERVERAPI getInstanceWithAuthBasic(Context context,String base_url,String username,String password){
return getIstance(context, base_url,username,password);
}
}
我已经尝试解决这个问题超过 2 周了,现在这是我在 rxjava issue 上的帖子页面和我之前的相同问题相关的问题是 here , 我怎样才能解决这个问题并使其正常工作
最佳答案
您的异常发生在您未在此处列出的类中。
无论如何,你需要分析Exception
的类型这是 onError
处理程序。使用 Retrofit2
处理有效的 HTTP 错误响应Observables(无论 rxjava
版本)非常简单。
首先你需要知道的是retrofit
api 方法返回 Obsrvable<MyObject>
将与 onNext
一起传播只有 2xx HTTP 响应。所有其他回复将在 onError
内发送处理程序。以下是如何处理它的代码(Kotlin 示例,仅供引用。Java 会):
retrofitApiService.suggest(
token,
query).subscribe ({ suggestions ->
log.info("Got result: {}", suggestions)
}, { error ->
//
if(error is HttpException) {
if(error.code() == 401) {
// We've got HTTP 401 Unauthorized
} else {
log.error("HTTP Error: {} {}, {}",
error.response().code(),
error.response().message(),
error.response().errorBody().toString())
}
} else {
// something really wrong happened
// e.g.: invalid json or something else
log.error("Error: ${error.message}", error)
}
})
如果你想让所有的响应都进入onNext,那么你应该使用Observable<ResponseBody>
.在这种情况下,所有有效的 HTTP 响应都将以 onNext
结束。 , 你所有的代码异常都将发送到 onError
.
关于android - 使用 rxjava2 时出现 Retrofit2 Unauthenticated 401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41806148/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!