欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

OkHttpIllegalArgumentException異常解決方法

在使用 okhttp 的時(shí)候,head 的一些項(xiàng)是中文,導(dǎo)致網(wǎng)絡(luò)請求失敗,錯(cuò)誤類似下面的

成都創(chuàng)新互聯(lián)公司成立與2013年,先為四平等服務(wù)建站,四平等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為四平企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

java.lang.IllegalArgumentException: Unexpected char ...

找了一圈發(fā)現(xiàn)是 okhttp 對 head 的編碼做了驗(yàn)證

Header values are (technically) required to be ISO-8859-1 but in practice only ASCII really works and OkHttp validates such (the exception has nothing to do with Retrofit). That string is a custom user agent and you'll need to restrict its contents to the ASCII character set when creating it.

具體的代碼 ( 在 okhttp3 庫里面的 okhttp3.Headers.java ) 如下:

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));
        }
    }
}

看源碼,解決的方法很簡單,保證所有的 head 都是符合編碼要求。

但是我的情況是,其中的某一些字符不合要求,這部分服務(wù)器不關(guān)心,而本地卻又不知道具體哪些是不和要求的。我的解決思路很簡單,挑出不合要求的字符,把這些字符單獨(dú)轉(zhuǎn)碼。

private static String encodeHeadInfo( String headInfo ) {
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0, length = headInfo.length(); i < length; i++) {
        char c = headInfo.charAt(i);
        if (c <= '\u001f' || c >= '\u007f') {
            stringBuffer.append( String.format ("\\u%04x", (int)c) );
        } else {
            stringBuffer.append(c);
        }
    }
    return stringBuffer.toString();
}

這樣

分享名稱:OkHttpIllegalArgumentException異常解決方法
本文網(wǎng)址:http://www.chinadenli.net/article34/iphcse.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)面包屑導(dǎo)航網(wǎng)站設(shè)計(jì)公司云服務(wù)器網(wǎng)站導(dǎo)航網(wǎng)站內(nèi)鏈

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

微信小程序開發(fā)