美文网首页
关于接口返回307的问题记录

关于接口返回307的问题记录

作者: sunqiyue | 来源:发表于2021-10-20 17:08 被阅读0次

触发307的原因就不写了,写我遇到之后的解决方法,只做我个人记录贴,或者能帮助到有需要的人

当时拿到的结果是这样的 307图片.png

围绕307这个字简直了。。度妈各种搜索,换个N种接口的写法,全部GG,可前端居然是可以调通的,好难啊。。。
不废话了解决方法的代码贴出:

   @NonNull
   private OkHttpClient initOkHttp() {
    //这个
    CookieHandler cookieHandler = new CookieManager(new PersistentCookieStore(BaseApplication.getContext()), CookiePolicy.ACCEPT_ALL);

    return new OkHttpClient().newBuilder()
            .readTimeout(Constant.DEFAULT_TIME, TimeUnit.SECONDS)//设置读取超时时间
            .connectTimeout(Constant.DEFAULT_TIME, TimeUnit.SECONDS)//设置请求超时时间
            .writeTimeout(Constant.DEFAULT_TIME, TimeUnit.SECONDS)//设置写入超时时间
            .cookieJar(new JavaNetCookieJar(cookieHandler))//这个
            .addInterceptor(new LogInterceptor())//添加打印拦截器
            .retryOnConnectionFailure(true)//设置出现错误进行重新连接。
            .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());
}
}

上面也是我度妈找的 如有侵权联系我删除了

相关文章

  • 关于接口返回307的问题记录

    触发307的原因就不写了,写我遇到之后的解决方法,只做我个人记录贴,或者能帮助到有需要的人 当时拿到的结果是这样的...

  • RobotFramework接口测试分享(二)

    进阶问题 1、接口返回:用户未登录——session处理 2、接口返回:验签失败——参数签名 3、接口返回:解密失...

  • 阿里Java规范-02-异常日志

    =================(一)异常处理==================关于接口使用抛异常还是返回错误...

  • iOS接口返回null的问题

    在ios中,接口经常返回null,有时候又返回空字符串,有时候又返回(null),甚至,利用isEqualToSt...

  • Java返回参数中文乱码问题

    1、遇到问题: 开始学习java,为移动端写第一个接口,然后发现返回的参数中包含中文的,出现了乱码问题。 2、记录...

  • 如何优雅的处理异常?SpringBoot全局异常与数据校验

    要思考的问题 在现在的前后端交互中,通常都规范了接口返回方式,如返回的接口状态(成功|失败)以及要返回的数据在那个...

  • iOS 解析 jsonp 格式数据

    今天业务中遇到了个关于网络返回数据 jsonp 格式解析的问题,记录一下。 遇到问题 一般情况下我们网络请求返回的...

  • vue axios 数字精度问题解决方法

    axios 修改里面配置 后面在处理其他接口的时候还是遇到了一个问题,关于后端数据返回的格式.有朋友遇到过这种问题...

  • 同一个接口两种不同的返回结果的判断方法

    “记录一下对同一个接口有两种不同的返回结果的判断方法。” ​签到成功返回的结果: 已签到后再次请求签到接口返回的结...

  • TextKit探究

    最近优化代码,遇到了一个问题,这里记录一下:类似一个搜索框页面,根据搜索的内容调接口请求,若接口返回数据为空的时候...

网友评论

      本文标题:关于接口返回307的问题记录

      本文链接:https://www.haomeiwen.com/subject/utitaltx.html