发送HTTPS POST请求到服务器 [英] Send HTTPS Post Request to the server

查看:277
本文介绍了发送HTTPS POST请求到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的HTTP JSON

  {
 用户: {
    名:必须放,密码:必须放}
}
 

这点我必须张贴到使用HTTPS POST请求的服务器。 当我尝试发送请求,我得到的SSL服务器证书例外。 我该如何解决这个问题?

我已经试过?

我用 HTTPPost 了HTTPClient 都试过了。 SSL异常。 我也尝试过使用的URLConnection 忽略SSL证书的检查。 我收到401和405的响应codeS。

该问题描述:

发送上述POST请求到服务器(请求安全的接受HTTPS)。 如何实现这一目标的机器人?

我已经试过这一点,我的code,我收到405错误?

  //始终验证主机 - 不检查证书
最后静态的HostnameVerifier DO_NOT_VERIFY =新的HostnameVerifier(){
    公共布尔验证(字符串主机名,的SSLSession会话){
        返回true;
    }
};

/ **
 *信任每个服务器 - 不检查任何证书
 * /
私有静态无效trustAllHosts(){
    //创建一个信任管理器不验证证书链
    的TrustManager [] trustAllCerts =新的TrustManager [] {新X509TrustManager(){
        公共java.security.cert.X509Certificate [] getAcceptedIssuers(){
            返回新java.security.cert.X509Certificate [] {};
        }

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

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

    //安装所有信任信任管理器
    尝试 {
        的SSLContext SC = SSLContext.getInstance(TLS);
        sc.init(NULL,trustAllCerts,新java.security.SecureRandom中的());
        HttpsURLConnection
                .setDefaultSSLSocketFactory(sc.getSocketFactory());
    }赶上(例外五){
        e.printStackTrace();
    }
}

私人无效makeRequest(){
    网址URL = NULL;
    HttpsURLConnection的URLConnection = NULL;
    尝试 {
        URL =新的URL(https://wbapi.cloudapp.net:443/api/User/LocalLogin);
    }赶上(MalformedURLException的E2){
        // TODO自动生成的catch块
        e2.printStackTrace();
    }
    StringBuilder的SB =新的StringBuilder();

    尝试 {
        trustAllHosts();
        的URLConnection =(HttpsURLConnection)url.openConnection();
        urlConnection.setHostnameVerifier(DO_NOT_VERIFY);
        urlConnection.setDoOutput(真正的);
        的URLConnection
                .setRequestProperty(内容类型,应用/ JSON);
        urlConnection.setFixedLengthStreamingMode(的URLConnection
                .getContentLength());
    }赶上(IOException异常E2){
        // TODO自动生成的catch块
        e2.printStackTrace();
    }

    尝试 {
        urlConnection.connect();
    }赶上(IOException异常E1){
        // TODO自动生成的catch块
        e1.printStackTrace();
    }
    JSONObject的jsonParam =新的JSONObject();
    尝试 {
        jsonParam.put(姓名,狗);
        jsonParam.put(密码,123);
        Log.v(长度,+ urlConnection.getContentLength());
        INT型Htt presult = urlConnection.getResponse code();
        Toast.makeText(LoginActivity.this,响应+ Htt的presult,
                Toast.LENGTH_LONG).show();
        如果(Htt的presult == HttpsURLConnection.HTTP_OK){
            的System.out.println(正常);
            Log.v(你好,+Trex公司);
            的BufferedReader BR =新的BufferedReader(新的InputStreamReader(
                    urlConnection.getInputStream(),UTF-8));
            串线= NULL;
            而((行= br.readLine())!= NULL){
                sb.append(行+\ N);
            }
            br.close();

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

        } 其他 {
            的System.out.println(在这里+ urlConnection.getResponseMessage());
        }
    }赶上(MalformedURLException异常E){

        e.printStackTrace();
    }赶上(IOException异常E){

        e.printStackTrace();
    }赶上(JSONException E){
        // TODO自动生成的catch块
        e.printStackTrace();
    }
}
 

logcat的条目

  12-27 13:41:27.228:V /长度(3034):72
12-27 13:41:27.248:我/的System.out(3034):HereMethod不允许
 

解决方案

第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.

这篇关于发送HTTPS POST请求到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆