關(guān)于接口返回307的問題記錄

觸發(fā)307的原因就不寫了,寫我遇到之后的解決方法,只做我個(gè)人記錄貼,或者能幫助到有需要的人

當(dāng)時(shí)拿到的結(jié)果是這樣的
307圖片.png

圍繞307這個(gè)字簡直了。。度媽各種搜索,換個(gè)N種接口的寫法,全部GG,可前端居然是可以調(diào)通的,好難啊。。。
不廢話了解決方法的代碼貼出:

   @NonNull
   private OkHttpClient initOkHttp() {
    //這個(gè)
    CookieHandler cookieHandler = new CookieManager(new PersistentCookieStore(BaseApplication.getContext()), CookiePolicy.ACCEPT_ALL);

    return new OkHttpClient().newBuilder()
            .readTimeout(Constant.DEFAULT_TIME, TimeUnit.SECONDS)//設(shè)置讀取超時(shí)時(shí)間
            .connectTimeout(Constant.DEFAULT_TIME, TimeUnit.SECONDS)//設(shè)置請求超時(shí)時(shí)間
            .writeTimeout(Constant.DEFAULT_TIME, TimeUnit.SECONDS)//設(shè)置寫入超時(shí)時(shí)間
            .cookieJar(new JavaNetCookieJar(cookieHandler))//這個(gè)
            .addInterceptor(new LogInterceptor())//添加打印攔截器
            .retryOnConnectionFailure(true)//設(shè)置出現(xiàn)錯(cuò)誤進(jìn)行重新連接。
            .build();

}

JavaNetCookieJar 需要引入

implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0'

下面是PersistentCookieStore

public class PersistentCookieStore implements CookieStore {
  private static final String LOG_TAG = "PersistentCookieStore";
  private static final String COOKIE_PREFS = "CookiePrefsFile";
  private static final String COOKIE_NAME_PREFIX = "cookie_";

private static HashMap<String, ConcurrentHashMap<String, HttpCookie>> cookies;
private static SharedPreferences cookiePrefs;

/**
 * Construct a persistent cookie store.
 *
 * @param context Context to attach cookie store to
 */
public PersistentCookieStore(Context context) {
    cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
    cookies = new HashMap<String, ConcurrentHashMap<String, HttpCookie>>();

    // Load any previously stored cookies into the store
    Map<String, ?> prefsMap = cookiePrefs.getAll();
    for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
        if (((String) entry.getValue()) != null && !((String) entry.getValue()).startsWith(COOKIE_NAME_PREFIX)) {
            String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
            for (String name : cookieNames) {
                String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
                if (encodedCookie != null) {
                    HttpCookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        if (!cookies.containsKey(entry.getKey()))
                            cookies.put(entry.getKey(), new ConcurrentHashMap<String, HttpCookie>());
                        cookies.get(entry.getKey()).put(name, decodedCookie);
                    }
                }
            }

        }
    }
}

@Override
public void add(URI uri, HttpCookie cookie) {

    // Save cookie into local store, or remove if expired
    if (!cookie.hasExpired()) {
        if (!cookies.containsKey(cookie.getDomain()))
            cookies.put(cookie.getDomain(), new ConcurrentHashMap<String, HttpCookie>());
        cookies.get(cookie.getDomain()).put(cookie.getName(), cookie);
    } else {
        if (cookies.containsKey(cookie.getDomain()))
            cookies.get(cookie.getDomain()).remove(cookie.getDomain());
    }

    // Save cookie into persistent store
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.putString(cookie.getDomain(), TextUtils.join(",", cookies.get(cookie.getDomain()).keySet()));
    prefsWriter.putString(COOKIE_NAME_PREFIX + cookie.getName(), encodeCookie(new SerializableHttpCookie(cookie)));
    prefsWriter.commit();
}

protected String getCookieToken(URI uri, HttpCookie cookie) {
    return cookie.getName() + cookie.getDomain();
}

@Override
public List<HttpCookie> get(URI uri) {
    ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
    for (String key : cookies.keySet()) {
        if (uri.getHost().contains(key)) {
            ret.addAll(cookies.get(key).values());
        }
    }
    return ret;
}

@Override
public boolean removeAll() {
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.clear();
    prefsWriter.commit();
    cookies.clear();
    return true;
}

public static void removeCookie() {
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
    prefsWriter.clear();
    prefsWriter.commit();
    cookies.clear();
}

@Override
public boolean remove(URI uri, HttpCookie cookie) {
    String name = getCookieToken(uri, cookie);

    if (cookies.containsKey(uri.getHost()) && cookies.get(uri.getHost()).containsKey(name)) {
        cookies.get(uri.getHost()).remove(name);

        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        if (cookiePrefs.contains(COOKIE_NAME_PREFIX + name)) {
            prefsWriter.remove(COOKIE_NAME_PREFIX + name);
        }
        prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
        prefsWriter.commit();

        return true;
    } else {
        return false;
    }
}

@Override
public List<HttpCookie> getCookies() {
    ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
    for (String key : cookies.keySet())
        ret.addAll(cookies.get(key).values());

    return ret;
}

@Override
public List<URI> getURIs() {
    ArrayList<URI> ret = new ArrayList<URI>();
    for (String key : cookies.keySet())
        try {
            ret.add(new URI(key));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    return ret;
}

/**
 * Serializes Cookie object into String
 *
 * @param cookie cookie to be encoded, can be null
 * @return cookie encoded as String
 */
protected String encodeCookie(SerializableHttpCookie cookie) {
    if (cookie == null)
        return null;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        ObjectOutputStream outputStream = new ObjectOutputStream(os);
        outputStream.writeObject(cookie);
    } catch (IOException e) {
        Log.d(LOG_TAG, "IOException in encodeCookie", e);
        return null;
    }

    return byteArrayToHexString(os.toByteArray());
}

/**
 * Returns cookie decoded from cookie string
 *
 * @param cookieString string of cookie as returned from http request
 * @return decoded cookie or null if exception occured
 */
protected HttpCookie decodeCookie(String cookieString) {
    byte[] bytes = hexStringToByteArray(cookieString);
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    HttpCookie cookie = null;
    try {
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie();
    } catch (IOException e) {
        Log.d(LOG_TAG, "IOException in decodeCookie", e);
    } catch (ClassNotFoundException e) {
        Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
    }

    return cookie;
}

/**
 * Using some super basic byte array <-> hex conversions so we don't have to rely on any
 * large Base64 libraries. Can be overridden if you like!
 *
 * @param bytes byte array to be converted
 * @return string containing hex values
 */
protected String byteArrayToHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (byte element : bytes) {
        int v = element & 0xff;
        if (v < 16) {
            sb.append('0');
        }
        sb.append(Integer.toHexString(v));
    }
    return sb.toString().toUpperCase(Locale.US);
}

/**
 * Converts hex values from strings to byte arra
 *
 * @param hexString string of hex-encoded values
 * @return decoded byte array
 */
protected byte[] hexStringToByteArray(String hexString) {
    int len = hexString.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
    }
    return data;
}

}

之后是SerializableHttpCookie

public class SerializableHttpCookie implements Serializable {
private static final long serialVersionUID = 6374381323722046732L;

private transient final HttpCookie cookie;
private transient HttpCookie clientCookie;

public SerializableHttpCookie(HttpCookie cookie) {
    this.cookie = cookie;
}

public HttpCookie getCookie() {
    HttpCookie bestCookie = cookie;
    if (clientCookie != null) {
        bestCookie = clientCookie;
    }
    return bestCookie;
}

private void writeObject(ObjectOutputStream out) throws IOException {
    out.writeObject(cookie.getName());
    out.writeObject(cookie.getValue());
    out.writeObject(cookie.getComment());
    out.writeObject(cookie.getCommentURL());
    out.writeObject(cookie.getDomain());
    out.writeLong(cookie.getMaxAge());
    out.writeObject(cookie.getPath());
    out.writeObject(cookie.getPortlist());
    out.writeInt(cookie.getVersion());
    out.writeBoolean(cookie.getSecure());
    out.writeBoolean(cookie.getDiscard());
}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    String name = (String) in.readObject();
    String value = (String) in.readObject();
    clientCookie = new HttpCookie(name, value);
    clientCookie.setComment((String) in.readObject());
    clientCookie.setCommentURL((String) in.readObject());
    clientCookie.setDomain((String) in.readObject());
    clientCookie.setMaxAge(in.readLong());
    clientCookie.setPath((String) in.readObject());
    clientCookie.setPortlist((String) in.readObject());
    clientCookie.setVersion(in.readInt());
    clientCookie.setSecure(in.readBoolean());
    clientCookie.setDiscard(in.readBoolean());
}
}

上面也是我度媽找的 如有侵權(quán)聯(lián)系我刪除了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容