OkHttp3 添加Authorization 异常 Unexpected char 0x0a at 42 in Authorization value 解决
程序员文章站
2023-12-24 13:00:39
异常记录导致错误:2020-09-27 11:00:55.027 29224-29224/cn.sh.changxing.smec.dt E/AndroidRuntime: FATAL EXCEPTION: main Process: cn.sh.changxing.smec.dt, PID: 29224 java.lang.IllegalArgumentException: Unexpected char 0x0a at 42 in Authorization value: Ba...
异常记录
导致错误:
2020-09-27 11:00:55.027 29224-29224/cn.sh.changxing.smec.dt E/AndroidRuntime: FATAL EXCEPTION: main
Process: cn.sh.changxing.smec.dt, PID: 29224
java.lang.IllegalArgumentException: Unexpected char 0x0a at 42 in Authorization value: Basic SjhERSFtRzNBRlVhS1FKNToyMDIwMDkyNw==
at okhttp3.Headers$Builder.checkNameAndValue(Headers.java:352)
at okhttp3.Headers$Builder.set(Headers.java:332)
at okhttp3.Request$Builder.header(Request.java:184)
错误分析:第42处 出现 0x0a 字符! 0x0a:表示换行符。 好吧,在结尾处有换行符导致的异常(但打印的字符串并看不出来.....)
异常写法:
private String getToken() {
try {
String salt = SPUtils.getInstance(MyApplication.getInstance()).getString(SPUtils.SP_IOT_BASIC_SALT);
if (!TextUtils.isEmpty(salt)) {
String str = salt + ":" + getSystemDate();
String token = "Basic " + Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
Log.d(TAG, "getToken: str = " + str + " token = " + token);
return token;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
修改处:
String token = "Basic " + Base64.encodeToString(str.getBytes(), Base64.DEFAULT).replaceAll("\r|\n", "");
转码后,去除字符串中所有的换行符!
本文地址:https://blog.csdn.net/Android_man_me/article/details/108823837