Google Volley架構之https請求

來源:互聯網
上載者:User

標籤:網上   put   ppi   generated   create   ror   client   auth   failure   

先插一句。Google出的volley架構本身是支援https請求的,可是僅僅是針對有第三方機構認證過的。

假設自己隨便在網上搞的一個認證,那volley是不支援要求的。


本文講下怎樣讓volley支援自己搞的https認證。


改動volley原始碼:com.android.myvolley.toolbox.HurlStack

   /**     * Create an {@link HttpURLConnection} for the specified {@code url}.     */    protected HttpURLConnection createConnection(URL url) throws IOException {        if (url.toString().contains("https")) {            MyHttpsManager.allowAllSSL();        }        return (HttpURLConnection) url.openConnection();    }
在HurlStack類中的createConnection方法中,做個過濾處理:

if (url.toString().contains("https")) {            MyHttpsManager.allowAllSSL();        }
直接貼代碼啦。

import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;public class MyHttpsManager implements X509TrustManager {    private static TrustManager[] trustManagers;    @Override    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {    }    @Override    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {    }    @Override    public X509Certificate[] getAcceptedIssuers() {        return new X509Certificate[0];    }    public static void allowAllSSL() {        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {            @Override            public boolean verify(String arg0, SSLSession arg1) {                // TODO Auto-generated method stub                return true;            }        });        SSLContext context = null;        if (trustManagers == null) {            trustManagers = new TrustManager[] { new MyHttpsManager() };        }        try {            context = SSLContext.getInstance("TLS");            context.init(null, trustManagers, new SecureRandom());        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        } catch (KeyManagementException e) {            e.printStackTrace();        }        HttpsURLConnection.setDefaultSSLSocketFactory(context                .getSocketFactory());    }}

然後請求的時候在頭裡面加個什麼鬼id。sign之類的,就能夠和服務端通訊了。

比如volley重寫getHeaders方法:

public void sendRequest(int method, String url, JSONObject jsonRequest, final String sessionToken, final OnResponseListener listener,final OnErrorListener errorListener) {        initUserAgent();        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(method, url, jsonRequest, new Response.Listener<JSONObject>() {            @Override            public void onResponse(JSONObject response) {                listener.onResponse(response);            }        }, new Response.ErrorListener() {            @Override            public void onErrorResponse(VolleyError error) {                errorListener.onErrorResponse(error);            }        }){            @Override            public Map<String, String> getHeaders() throws AuthFailureError {                HashMap<String, String> headers = new HashMap<String,String>();                headers.put("Content-Type", "application/json");                headers.put("x-app-id", APPID);                headers.put("x-app-sign",SIGN);                headers.put("x-session-token",sessionToken);                headers.put("User-Agent",userAgent);                return headers;            }        };        Volley.newRequestQueue(context).add(jsonObjectRequest);    }


Google Volley架構之https請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.