我們知道Okhttp走的并不是原生的http請求撵溃,因此他在header里面并沒有真正的User-Agent,而是“okhttp/版本號”這樣的字符串锥累,因為后臺需要統(tǒng)計信息缘挑,要求傳入正確的User-Agent,那么我們?nèi)绾潍@取User-Agent并設(shè)置給Okhttp呢桶略?
0x00-正確獲取User-Agent
private static String getUserAgent() {
String userAgent = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
try {
userAgent = WebSettings.getDefaultUserAgent(context);
} catch (Exception e) {
userAgent = System.getProperty("http.agent");
}
} else {
userAgent = System.getProperty("http.agent");
}
StringBuffer sb = new StringBuffer();
for (int i = 0, length = userAgent.length(); i < length; i++) {
char c = userAgent.charAt(i);
if (c <= '\u001f' || c >= '\u007f') {
sb.append(String.format("\\u%04x", (int) c));
} else {
sb.append(c);
}
}
return sb.toString();
}
代碼說明:
1语淘、在Api17之后可以通過WebSettings.getDefaultUserAgent(context)
獲取,但是經(jīng)過測試極個別手機會出現(xiàn)找不到類的情況际歼,因此try-catch一下惶翻,那么第二種方式是System.getProperty("http.agent")
,這兩種方式有什么不同呢?從結(jié)果上來看是第一種得到的信息更全一點鹅心;
第一種:
Mozilla/5.0 (Linux; Android 6.0.1; MI 4LTE Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko)
Version/4.0 Chrome/51.0.2704.81 Mobile Safari/537.36
第二種:
Dalvik/2.1.0 (Linux; U; Android 6.0.1; MI 4LTE MIUI/6.10.13)
2吕粗、在一些國產(chǎn)手機上面這個User-Agent里面會包含中文,就會報錯
java.lang.IllegalArgumentException: Unexpected char 0x7231 at 33 in User-Agent value: Mozilla/5.0 (Linux; Android 5.1; 愛國者-X86 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Safari/537.36
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2367)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2419)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5323)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Unexpected char 0x7231 at 33 in User-Agent value: Mozilla/5.0
(Linux; Android 5.1; 愛國者-X86 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Safari/537.36
at okhttp3.Headers$Builder.checkNameAndValue(Headers.java:320)
at okhttp3.Headers$Builder.add(Headers.java:270)
at okhttp3.Request$Builder.addHeader(Request.java:175)
什么原因引起的呢旭愧?okhttp3.Headers$Builder.checkNameAndValue
進(jìn)到這個方法里面可以看到okhttp對中文進(jìn)行了過濾颅筋,如果不符合條件就拋出異常IllegalArgumentException
private void checkNameAndValue(String name, String value) {
if (name == null) throw new NullPointerException("name == null");
if (name.isEmpty()) throw new IllegalArgumentException("name is empty");
for (int i = 0, length = name.length(); i < length; i++) {
char c = name.charAt(i);
if (c <= '\u001f' || c >= '\u007f') {
throw new IllegalArgumentException(Util.format(
"Unexpected char %#04x at %d in header name: %s", (int) c, i, name));
}
}
if (value == null) throw new NullPointerException("value == null");
for (int i = 0, length = value.length(); i < length; i++) {
char c = value.charAt(i);
if (c <= '\u001f' || c >= '\u007f') {
throw new IllegalArgumentException(Util.format(
"Unexpected char %#04x at %d in %s value: %s", (int) c, i, name, value));
}
}
}
因此上段代碼才會對返回結(jié)果進(jìn)行過濾,如果不符合條件输枯,會進(jìn)行轉(zhuǎn)碼议泵。
0x01-給Okhttp設(shè)置User-Agent
Request request = new Request.Builder().url(url).removeHeader("User-Agent").addHeader("User-Agent",
getUserAgent()).build();
httpClient.newCall(request).enqueue(handler);