寫 Mobile app 不免要網路連線一下,這時候最簡易的方式就是像 php 的 file_get_contents 函數,只要呼叫一下,就得到想要的東西。然而,在測試 https 時,發現對方憑證並非經過第三方認證的,因此噴出錯誤訊息:android javax.net.ssl.SSLPeerUnverifiedException: No peer certificate,這資安保護的確還不錯,但對開發、測試實在不方便,在網路上有找到的解法是實作一個 SSLSocketFactory 來解決,雖然不知是不是正解,但至少可以 work 了 :P (總覺得應該要能某個參數設定一下就行,就像 php curl 的 CURLOPT_SSL_VERIFYPEER 和 CURLOPT_SSL_VERIFYHOST 參數)
發送 http GET request:
//
// List<NameValuePair> params = new LinkedList<NameValuePair>(); // ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("a", "1"));
// params.add(new BasicNameValuePair("b", "2"));
// System.out.println( get_url_contents( "http://www.google.com.tw" , null ) );
// System.out.println( get_url_contents( "http://www.google.com.tw" , params ) );
//
String get_url_contents( String url , List<NameValuePair> params ) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute( new HttpGet( params == null || params.size() == 0 ? url : url + "?" + URLEncodedUtils.format(params, "utf-8") ) );
HttpEntity result = response.getEntity();
if( result != null ) {
//return EntityUtils.toString(result); // 有編碼問題
InputStream mInputStream = result.getContent();
String out = getStringFromInputStream(mInputStream);
mInputStream.close();
return out;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
發送 http POST request:
String post_url_contents( String url, List<NameValuePair> params ) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost mHttpPost = new HttpPost(url);
if( params != null && params.size() > 0 )
mHttpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponse response = client.execute(mHttpPost);
HttpEntity result = response.getEntity();
if( result != null ) {
//return EntityUtils.toString(result); // 有編碼問題
InputStream mInputStream = result.getContent();
String out = getStringFromInputStream(mInputStream);
mInputStream.close();
return out;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
使用 Cookie 的方式:
// CookieStore cookieStore = new BasicCookieStore();
String get_url_contents( String url , List<NameValuePair> params , CookieStore cookieStore ) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
if( cookieStore == null )
response = client.execute( new HttpGet( params == null || params.size() == 0 ? url : url + "?" + URLEncodedUtils.format(params, "utf-8") ) );
else {
HttpContext mHttpContext = new BasicHttpContext();
mHttpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
response = client.execute( new HttpGet( params == null || params.size() == 0 ? url : url + "?" + URLEncodedUtils.format(params, "utf-8") ) , mHttpContext );
}
HttpEntity result = response.getEntity();
if( result != null ) {
//return EntityUtils.toString(result); // 有編碼問題
InputStream mInputStream = result.getContent();
String out = getStringFromInputStream(mInputStream);
mInputStream.close();
return out;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
其他:
String getStringFromInputStream(InputStream in) {
byte []data = new byte[1024];
int length;
if( in == null )
return null;
ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
try {
while( (length = in.read(data)) != -1 )
mByteArrayOutputStream.write(data, 0, length);
} catch (IOException e) {
e.printStackTrace();
}
return new String(mByteArrayOutputStream.toByteArray());
}
解決 android javax.net.ssl.SSLPeerUnverifiedException: No peer certificate:
程式碼:
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.client.HttpClient;
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 mSSLContext = SSLContext.getInstance("TLS");
@Override
public Socket createSocket() throws IOException {
return mSSLContext.getSocketFactory().createSocket();
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return mSSLContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager mTrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
mSSLContext.init(null, new TrustManager[] { mTrustManager }, null);
}
public static HttpClient createMyHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load( null, null);
SSLSocketFactory mSSLSocketFactory = new MySSLSocketFactory(trustStore);
mSSLSocketFactory.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", mSSLSocketFactory, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
}
return new DefaultHttpClient();
}
}
使用:
//HttpClient client = new DefaultHttpClient();
HttpClient client = MySSLSocketFactory. createMyHttpClient();
參考資料:
Android Series: GET, POST and Multipart POST requests
android javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
不好意思
回覆刪除可以請問一下有完整一點的嗎??
因為我看不太懂怎麼寫好= =
您好,我剛好再找關於https非第三方驗證的連線方式,我有找到看似較正確的方法,和您分享=)
回覆刪除http://nelenkov.blogspot.ie/2011/12/using-custom-certificate-trust-store-on.html
謝謝你的分享 :)
刪除