Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send HTTPS Post Request to the server

Tags:

android

This is my HTTP JSON

 {  
 "User": {    
    "Name": "Compulsary","Password": "Compulsary"  }
}

Which I have to post to the server using HTTPS POST request. When I try to send the request, I get SSL Server Certificate Exception. How can I fix this issue ?

What I have tried ?

I have tried using HTTPPost with HTTPClient. SSL Exception. I also tried using URLConnection and ignored the checking of SSL Certificates. I am getting 401 and 405 response codes.

The Problem Statement :

Send the above POST Request to the Server (The request is secure accepts https). How to achieve this in android ?

I have tried this, My Code, I am getting 405 error ?

// always verify the host - dont check for certificate
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
};

/**
 * Trust every server - dont check for any certificate
 */
private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.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 java.security.SecureRandom());
        HttpsURLConnection
                .setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void makeRequest() {
    URL url = null;
    HttpsURLConnection urlConnection = null;
    try {
        url = new URL("https://wbapi.cloudapp.net:443/api/User/LocalLogin");
    } catch (MalformedURLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    StringBuilder sb = new StringBuilder();

    try {
        trustAllHosts();
        urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setHostnameVerifier(DO_NOT_VERIFY);
        urlConnection.setDoOutput(true);
        urlConnection
                .setRequestProperty("Content-Type", "application/json");
        urlConnection.setFixedLengthStreamingMode(urlConnection
                .getContentLength());
    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    try {
        urlConnection.connect();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    JSONObject jsonParam = new JSONObject();
    try {
        jsonParam.put("Name", "dog");
        jsonParam.put("Password", "123");
        Log.v("Length", "" + urlConnection.getContentLength());
        int HttpResult = urlConnection.getResponseCode();
        Toast.makeText(LoginActivity.this, "Response" + HttpResult,
                Toast.LENGTH_LONG).show();
        if (HttpResult == HttpsURLConnection.HTTP_OK) {
            System.out.println("ok");
            Log.v("Hi", "" + "Trex");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream(), "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            System.out.println("" + sb.toString());
            Toast.makeText(LoginActivity.this, "" + sb.toString(),
                    Toast.LENGTH_LONG).show();

        } else {
            System.out.println("Here" + urlConnection.getResponseMessage());
        }
    } catch (MalformedURLException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Logcat entries

12-27 13:41:27.228: V/Length(3034): 72
12-27 13:41:27.248: I/System.out(3034): HereMethod Not Allowed
like image 958
Rajeev N B Avatar asked Dec 27 '12 07:12

Rajeev N B


1 Answers

Step 1: Create a class MySSLSocketFactory and include below code:

public class MySSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore)
                    throws NoSuchAlgorithmException, KeyManagementException,
                    KeyStoreException, UnrecoverableKeyException {
            super(truststore);

            TrustManager tm = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain,
                                    String authType) throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] chain,
                                    String authType) throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                            return null;
                    }
            };

            sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port,
                    boolean autoClose) throws IOException, UnknownHostException {
            return sslContext.getSocketFactory().createSocket(socket, host, port,
                            autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
            return sslContext.getSocketFactory().createSocket();
    }

}

Step 2: Create a class WebClientDevWrapper and include the below code:

public class WebClientDevWrapper {

    public static HttpClient getNewHttpClient() {
         try {
             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
             trustStore.load(null, null);

             SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
             sf.setHostnameVerifier(
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

             HttpParams params = new BasicHttpParams();
             HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
             HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

             SchemeRegistry registry = new SchemeRegistry();
             registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
             registry.register(new Scheme("https", sf, 443));

             ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

             return new DefaultHttpClient(ccm, params);
         } catch (Exception e) {
             return new DefaultHttpClient();
         }
     }

}

Step 3: Create a method inside your Activity or elsewhere, this method is going to be used for making a web call.

/**
     * Request JSON based web service to get response
     * 
     * @param url
     *            - base URL
     * @param request
     *            - JSON request
     * @return response
     * @throws ClientProtocolException
     * @throws IOException
     * @throws IllegalStateException
     * @throws JSONException
     */
    public HttpResponse request(String url, JSONObject request)
            throws ClientProtocolException, IOException, IllegalStateException,
            JSONException {

        DefaultHttpClient client = (DefaultHttpClient) WebClientDevWrapper.getNewHttpClient();

            HttpPost post = new HttpPost(url);
            post.setEntity(new StringEntity(request.toString(), "utf-8"));
            HttpResponse response = client.execute(post);
            return response;
        }
    }

Step 4: Call a method and get response.

like image 94
Paresh Mayani Avatar answered Nov 02 '22 12:11

Paresh Mayani