Java Android Studio中用于HTTPs下载的自签名证书
好的,所以我一直在努力从HTTPS网站下载一张图片,以显示在我的android应用程序中。我一直在使用安卓开发网站来做这件事。 但是,当我尝试使用Java Android Studio中用于HTTPs下载的自签名证书,java,android,ssl,certificate,self-signed,Java,Android,Ssl,Certificate,Self Signed,好的,所以我一直在努力从HTTPS网站下载一张图片,以显示在我的android应用程序中。我一直在使用安卓开发网站来做这件事。 但是,当我尝试使用.setsslssocketfactory()方法时,IDE说它无法解析此方法。我不知道我在这里做错了什么,我想我有所有的进口,我需要这样做。 任何帮助都将不胜感激 这是我的代码: import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOE
.setsslssocketfactory()
方法时,IDE说它无法解析此方法。我不知道我在这里做错了什么,我想我有所有的进口,我需要这样做。
任何帮助都将不胜感激
这是我的代码:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
public class CertificateHandler {
private final String myCert = "MyCA.crt";
public void getToken(HttpURLConnection urlConnection) {
try {
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = new BufferedInputStream(new FileInputStream("myCert"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
urlConnection.setSSLSocketFactory(context.getSocketFactory());
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
}
}
以下是我为自己工作时得到的答案: 我用于接收所有HTTPS get请求的HTTPS get类
public class MyHttpsGet extends AsyncTask<String, Void, String> {
Context context;
int cert;
boolean allowHost;
private String username;
private String password;
//this is used if you need a password and username
//mainly for logins to a webserver
public MyHttpsGet(String username, String password, Context context, int cert)
{
this.context = context;
this.cert = cert;
this.allowHost = allowHost;
this.username = username;
this.password = password;
}
//used for image downloading
public MyHttpsGet(){}
@Override
protected String doInBackground(String... params) {
String url = params[0];
return httpsDownloadData(url, context, cert);
}
public String httpsDownloadData (String urlString, Context context, int certRawResId)
{
String respone = null;
try {
// build key store with ca certificate
KeyStore keyStore = buildKeyStore(context, certRawResId);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
// Create a connection from url
URL url = new URL(urlString);
if (username != null) {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
}
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
int statusCode = urlConnection.getResponseCode();
Log.d("Status code: ", Integer.toString(statusCode));
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
respone = streamToString(inputStream);
inputStream.close();
}
}catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
Log.d("MyHttps Respones: ", respone);
return respone;
}
private static KeyStore buildKeyStore(Context context, int certRawResId){
// init a default key store
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
// read and add certificate authority
Certificate cert = readCert(context, certRawResId);
keyStore.setCertificateEntry("ca", cert);
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return keyStore;
}
private static Certificate readCert(Context context, int certResourceId) throws IOException {
// read certificate resource
InputStream caInput = context.getResources().openRawResource(certResourceId);
Certificate ca = null;
try {
// generate a certificate
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ca = cf.generateCertificate(caInput);
} catch (CertificateException e) {
e.printStackTrace();
} finally {
caInput.close();
}
return ca;
}
//this is used for downloading strings from an http or https connection
private String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
}
其中,R.raw.gdroot_g2是存储在android项目的raw文件夹中的证书 是否应该是
HttpsUrlConnection
??是的,你的权利Raghunandan,我的问题是我正在下载一个URL列表,它们混合了http和https。主url是http,因此我必须将每个url分成两个不同的组,并使用不同的方法下载它们。非常感谢McUh你找到解决问题的方法了吗?我在安卓N上也面临着类似的问题。不是真的。我不得不重新设计整个项目以使用正确的证书。我会把它贴在下面供你使用。
MyHttpsGet task = new MyHttpsGet(username, password,myContext, R.raw.gdroot_g2);
try {
myJson = task.execute(myUrl).get();
Log.d("Promo Json: " , myJson);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
new runningMan().execute();