我的代碼適用於http,但不適用於https。 我正在嘗試使用HttpClient在Android手機上製作Https connections
。麻煩的是我不斷收到net.ssl.SSLPeerUnverifiedException: No peer certificate
。和Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
如何創建https連接?
這裏是Custom HttpClient的相關代碼。
public static HttpClient getNewHttpClient() {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
DefaultHttpClient http = new DefaultHttpClient(conMgr, params);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("name", "pass");
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
http.getCredentialsProvider().setCredentials(authScope, credentials);
return http;
}
這是從服務器
public static void Get() {
HttpClient http = getNewHttpClient();
HttpResponse response;
try {
HttpGet httpost = new HttpGet(url);
response = http.execute(httpost);
BufferedReader in = null;
Log.i(TAG, "resp-" + response);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
Log.i(TAG, "res=" + sb.toString());
tv.setText(page);
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException=" + e);
e.printStackTrace();
} catch (IOException e) {
Log.i(TAG, "ClientProtocolException=" + e);
e.printStackTrace();
}
}
任何想法獲取信息的代碼?
我收到此錯誤:javax.net.ssl.SSLPeerUnverifiedException:沒有對方的證書 –
HTTP:/ /developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html 2個月前,我從上述鏈接的參考中解決了我的問題。 –