且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

发送HTTPS POST请求到服务器

更新时间:2022-10-29 11:21:33

第1步:创建类 MySSLSocketFactory ,其中包括$ C $以下C:

 公共类MySSLSocketFactory扩展的SSLSocketFactory {
    的SSL连接的SSL连接= SSLContext.getInstance(TLS);

    公共MySSLSocketFactory(密钥库信任库)
                    抛出抛出:NoSuchAlgorithmException,KeyManagementException,
                    KeyStoreException,UnrecoverableKeyException {
            超(信任库);

            的TrustManager TM =新X509TrustManager(){
                    公共无效checkClientTrusted(x509证书[]链,
                                    字符串的authType)抛出CertificateException {
                    }

                    公共无效checkServerTrusted(x509证书[]链,
                                    字符串的authType)抛出CertificateException {
                    }

                    公共x509证书[] getAcceptedIssuers(){
                            返回null;
                    }
            };

            sslContext.init(空,新的TrustManager [] {} TM,NULL);
    }

    @覆盖
    公共插座中的createSocket(Socket套接字,字符串主机,INT端口,
                    布尔自动关闭)抛出IOException异常,UnknownHostException异常{
            返回sslContext.getSocketFactory()中的createSocket(插座,主机,端口,
                            自动关闭);
    }

    @覆盖
    公共插座中的createSocket()抛出IOException异常{
            返回sslContext.getSocketFactory()中的createSocket()。
    }

}
 

第二步:创建类 WebClientDevWrapper ,并包括以下code:

 公共类WebClientDevWrapper {

    公共静态的HttpClient getNewHttpClient(){
         尝试 {
             密钥库的trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
             trustStore.load(NULL,NULL);

             SSLSocketFactory的SF =新MySSLSocketFactory(的trustStore);
             sf.setHostnameVerifier(
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

             的HttpParams PARAMS =新BasicHttpParams();
             HttpProtocolParams.setVersion(参数,可以HttpVersion.HTTP_1_1);
             HttpProtocolParams.setContentCharset(参数,可以HTTP.UTF_8);

             SchemeRegistry注册表=新SchemeRegistry();
             registry.register(新计划(HTTP,PlainSocketFactory.getSocketFactory(),80));
             registry.register(新计划(https开头,SF,443));

             ClientConnectionManager CCM =新ThreadSafeClientConnManager(参数,可以登记);

             返回新DefaultHttpClient(CCM,则params);
         }赶上(例外五){
             返回新DefaultHttpClient();
         }
     }

}
 

第三步:您的活动里创建一个方法或其他地方,这种方法将被用于制造网络电话

  / **
     *要求基于JSON的Web服务来获取响应
     *
     * @参数的URL
     *  - 基本URL
     * @参数要求
     *  -  JSON请求
     * @返回响应
     * @throws ClientProtocolException
     * @throws IOException异常
     * @throws IllegalStateException异常
     * @throws JSONException
     * /
    公众的Htt presponse请求(字符串URL,JSONObject的要求)
            抛出ClientProtocolException,IOException异常,IllegalStateException异常,
            JSONException {

        DefaultHttpClient客户=(DefaultHttpClient)WebClientDevWrapper.getNewHttpClient();

            HttpPost后=新HttpPost(URL);
            post.setEntity(新StringEntity(request.toString(),UTF-8));
            HTT presponse响应= client.execute(后);
            返回响应;
        }
    }
 

第四步:拨打的方法,并得到响应

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

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.