Android: SSL/https POST request using Volley

RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext(), new HurlStack(null, getSSL()));

final JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {

if (null != jsonObject) {
try {
String accessToken = (String) jsonObject.get("access_token");
AppPreference.getInstance().setPreference(AppKeys.ACCESS_TOKE                                                          N, accessToken);
haveAccessToken = true;
mHandler.sendEmptyMessage(1);
Log.i(getClass().getSimpleName(), accessToken);
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getActivity().getApplicationContext(), "Login Success",                                                    Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getActivity().getApplicationContext(), "Login fail", Toast.LENGTH_SHORT).show();
mHandler.sendEmptyMessage(11);
Log.i(getClass().getSimpleName(), "onErrorResponse " + volleyError.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> header = new HashMap<>();

return header;
}


@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}


@Override
protected String getParamsEncoding() {
return "utf-8";
}

@Override
public byte[] getBody() {
//                String s = "your request body parms";
byte[] b = s.getBytes();
return b;
}
};
queue.add(req);



    public SSLSocketFactory getSSL() {
        try {
            // Load CAs from an InputStream            // (could be from a resource or ByteArrayInputStream or ...)            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            // From https://www.washington.edu/itconnect/security/ca/load-der.crt//            InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));            InputStream caInput = getActivity().getApplicationContext().getResources().openRawResource("your server cert from raw folder");
            Certificate ca;
            try {
                ca = cf.generateCertificate(caInput);
                System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
            } finally {
                caInput.close();
            }

            // Create a KeyStore containing our trusted CAs            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            // Create a TrustManager that trusts the CAs in our KeyStore            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            // Create an SSLContext that uses our TrustManager            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);

            return context.getSocketFactory();
        } catch (CertificateException ex) {
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } catch (KeyManagementException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (KeyStoreException ex) {
            ex.printStackTrace();
        }
        return null;
    }


Comments

Popular posts from this blog

Working with Android Hierarchy Viewer

Android: Standalone login with SQLiteOpenHelper