HttpsURLconnection发布并进入Android

时间:2016-06-29 08:15:58

标签: android sockets ssl-certificate httpsurlconnection

我正在开发一个简单的应用程序,它使用https协议从服务器发布和获取数据。我在互联网上搜索但是资源很少,我尝试了大部分资源但是没能成功。

我尝试使用 HttpClient 这是成功的,但我想用 HttpsURLconnection

来做

我是否需要从设备中获取公共RSA密钥,如果是这样,我该怎么办呢。

有人可以告诉我如何使用httpsURLconnection实现此目的。

protected String doInBackground(String... arg0) {     
  try {
    ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509","BC");
    X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
    String alias = "alias";//cert.getSubjectX500Principal().getName();

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);
    trustStore.setCertificateEntry(alias, cert);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(trustStore, null);
    KeyManager[] keyManagers = kmf.getKeyManagers();

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(trustStore);
    TrustManager[] trustManagers = tmf.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);
    URL url = new URL("MY HTTPS URL");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setSSLSocketFactory(sslContext.getSocketFactory());

    // set Timeout and method
    conn.setReadTimeout(7000);
    conn.setConnectTimeout(7000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // Add any data you wish to post here
    conn.connect();
    String reult = String.valueOf(conn.getInputStream());
    Log.d("connection : ", String.valueOf(reult));

  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }  catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
  } catch (KeyManagementException e) {
    e.printStackTrace();
  } catch (CertificateException e) {
    e.printStackTrace();
  } catch (KeyStoreException e) {
    e.printStackTrace();
  } catch (NoSuchProviderException e) {
    e.printStackTrace();
  } catch (UnrecoverableKeyException e) {
    e.printStackTrace();
  }
  return null;
}

我大部分时间都收到错误:

Caused by: `java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.`

1 个答案:

答案 0 :(得分:2)

我在我的应用程序中使用以下代码将数据发布到我的服务器并阅读回复。

boolean DEBUG = false;

private static String sendHttpsPost(String d, Map<String, String> params) {
  if(DEBUG)disableHttpsVerify(null);
  BufferedReader bis = null;
  InputStream in = null;
  OutputStream out = null;
  try {
    URL url = new URL(d);
    HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    out = connection.getOutputStream();

    StringBuilder sb = new StringBuilder();
    for(Map.Entry<String, String> entry : params.entrySet()) {
      sb.append(entry.getKey());
      sb.append('=');
      sb.append(entry.getValue());
      sb.append('&');
    }
    String str = sb.toString();
    byte[] data = str.substring(0, str.length() - 1).getBytes();
    out.write(data);

    connection.connect();
    in = connection.getInputStream();
    bis = new BufferedReader(new InputStreamReader(in));
    sb.setLength(0);
    while((str = bis.readLine()) != null) {
      sb.append(str);
    }
    return sb.toString();
  } catch (Exception e) {
    return "";
  } finally {
    try {
      if(bis != null) {
        bis.close();
      }
      if(in != null) {
        in.close();
      }
    } catch (Exception x) {

    }
  }
}

注意:

  
      
  1. params包含您要发送到服务器的参数
  2.   
  3. disableHttpsVerify用于绕过所有安全检查,以防服务器的CA不受信任。请参阅以下代码。
  4.   

您可以看到使用https协议几乎与使用http。

相同

disableHttpsVerify的代码:

try {
  TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
     @Override
     public X509Certificate[] getAcceptedIssuers() {
       return null;
     }

     @Override
     public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
       // Not implemented
     }

     @Override
     public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
       // Not implemented
     }
   }};
   SSLContext sc = SSLContext.getInstance("TLS");

   sc.init(null, trustAllCerts, new java.security.SecureRandom());

   HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 } catch (Exception e) {
   LogSaveUtil.savePayLog("disableHttpsVerify" + e.toString());
 }