1. 程式人生 > >okhttp http 重定向到https

okhttp http 重定向到https

package com.adups.wql.httpredirecttohttps;
import android.util.Log;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import 
java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * Created by bigTree on 2017/2/6. */ public class
okhttp { String url = ""; static OkHttpClient okHttpClient = new OkHttpClient(); static { okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS); okHttpClient.setReadTimeout(30, TimeUnit.SECONDS); okHttpClient.setWriteTimeout(30, TimeUnit.SECONDS); // okHttpClient.interceptors().add(new LoggingInterceptor());
//為false就是自定義重定向,true 就是自己內部就重定向了,只返回最後就結果 okHttpClient.setFollowRedirects(false); trustAllHosts();//設定忽略安全證書驗證 okHttpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } public static String run(String url) throws IOException { Request request = new Request.Builder().url(url).get().build(); Response response = okHttpClient.newCall(request).execute(); // Log.e("response.code()", "" + response.code()); // Log.e("httpUrl", "" + response.request().httpUrl()); // Log.e("response.body()", "" + response.body().string()); Log.e("Location", "" + response.headers().get("Location")); // Log.e("headers", "" + request.url()); int code = response.code(); if (code == 302) { String location = response.headers().get("Location"); run(location); } else if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } return ""; } public static void trustAllHosts() { // Create a trust manager that does not validate certificate chains // Android use X509 cert TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }}; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); okHttpClient.setSslSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } }