English 中文(简体)
Anders HTTPS 员额 不工作
原标题:Android HTTPS Post - Not working

I ve been trying for ages to get this to work - but no matter what I do, my HTTP*S* POST always yields HttpUtils: javax.net.ssl.SSLException: Not trusted server certificate

基本上,我照此办理:http://blog.crazybob.org/ 201002/android-trusting-sl-certificates.html”。

  • I successfully grabbed the public certificate (mycert.pem) from the server.
  • I successfully created a keystore from the certificate using Bouncy Castle
  • I failed at implementing a custom Apache HttpClient. Here is my code:

    import android.content.Context;
    import org.apache.http.conn.ClientConnectionManager;
    import org.apache.http.conn.scheme.PlainSocketFactory;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.conn.SingleClientConnManager;
    import org.apache.http.params.HttpParams;
    import java.io.InputStream;
    import java.security.KeyStore;
    
    public class MyHttpClient extends DefaultHttpClient {
      final Context context;
    
      public MyHttpClient(Context context) {
        this.context = context;
      }
    
      public MyHttpClient(Context context2, HttpParams myParams) {
          super(myParams);
          this.context= context2;
    }
    
    @Override protected ClientConnectionManager createClientConnectionManager() {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(
            new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", newSslSocketFactory(), 443));
        return new SingleClientConnManager(getParams(), registry);
      }
    
      private SSLSocketFactory newSslSocketFactory() {
        try {
          KeyStore trusted = KeyStore.getInstance("BKS");
          InputStream in = context.getResources().openRawResource(R.raw.mystore);
          try {
            trusted.load(in, "password".toCharArray());
          } finally {
            in.close();
          }
          return new SSLSocketFactory(trusted);
        } catch (Exception e) {
          throw new AssertionError(e);
        }
      }
    }
    

    And in my HTTP Request class that constructs the POST:

    public class HttpRequest {
    MyHttpClient httpClient;
    HttpContext localContext;
    private String ret;
    
    HttpResponse response = null;
    HttpPost httpPost = null;
    HttpGet httpGet = null;
    
    public HttpRequest(Context context){
        HttpParams myParams = new BasicHttpParams();
    
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 10000);
        httpClient = new MyHttpClient(context, myParams);       
        localContext = new BasicHttpContext();    
    }
    
    public String sendPost(String url, String data, String contentType) {
        ret = null;
    
        httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
    
        httpPost = new HttpPost(url);
        response = null;
    
        StringEntity tmp = null;        
    
        httpPost.setHeader("User-Agent", "SET YOUR USER AGENT STRING HERE");
        httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
    
        if (contentType != null) {
            httpPost.setHeader("Content-Type", contentType);
        } else {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        }
    
        try {
            tmp = new StringEntity(data,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.e("Log", "HttpUtils : UnsupportedEncodingException : "+e);
        }
    
        httpPost.setEntity(tmp);
    
        try {
            response = httpClient.execute(httpPost,localContext);
    
            if (response != null) {
                ret = EntityUtils.toString(response.getEntity());
            }
        } catch (Exception e) {
            Log.e("Log", "HttpUtils: " + e);
        }
    
        return ret;
    }
    }
    

我的“开放式”组织对非网站进行罚款。 任何帮助都将受到高度赞赏。

最佳回答

查看错误信息:

HttpUtils: javax.net.sl.SSLException: 不可靠的服务器证书

这完全意味着它所说的——服务器没有使用可信赖的证书。 如果你试图与IE公司同一个服务器联系,我就会发现类似的错误。

问题回答

有时,https url在海底网格中显示空白的白色屏幕。 这是因为你必须相信 s证书,或者你需要推翻你的网络调查客户的 error错误。

The following webview client provides the needed functions to access https url. here shouldOverrideUrlLoading is used for to allow the redirecting url within the webview, onReceivedSslError this oneiIgnore SSL certificate errors to access the https url.


Webviewclient:

private class MyWebViewClient extends WebViewClient 
             {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            System.out.println("onPageStarted: " + url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            System.out.println("shouldOverrideUrlLoading: " + url); 
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView webView, String url) {
            System.out.println("onPageFinished: " + url);               

        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                SslError error) {
            handler.proceed(); // Ignore SSL certificate errors
        }   

    }

利用这个班子获得HttpClient。 如果有帮助,进行检查。

package com.android.MyCellFamily.DAHttp;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

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();
    }


public static DefaultHttpClient 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();
    }
}
}




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签