1. 程式人生 > >聯合登入,請求令牌時對方返回空以及SSLPeerUnverifiedException的解決辦法

聯合登入,請求令牌時對方返回空以及SSLPeerUnverifiedException的解決辦法

最近做了一個聯合登入,在本地測試通過,但是一上線就報錯。後來通過日誌資訊觀察到,去請求令牌時,對方返回了空。現在把修改前後的請求方法寫在下面:

之前,請求不到令牌的寫法:

private static JSONObject getJsonFromUrl(String urlStr) {
		// org.apache.http.client.HttpClient
		HttpClient httpClient = new DefaultHttpClient();
		// org.apache.http.client.methods.HttpPost
		HttpPost httpPost = new HttpPost(urlStr);
		JSONObject json = null;
		try {			
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			// 使用InputStream從資料流中讀取資料
			InputStream is = entity.getContent();
			byte[] bytes = new byte[256];
			StringBuffer sb = new StringBuffer();
			while (is.read(bytes) > 0) {				
				sb.append(new String(bytes, HTTP.UTF_8));
				bytes = new byte[256];
			}
			json = JSONObject.fromObject(sb.toString());
		} catch (Exception e) {
			LOG.error("http client execute error:" + e.getMessage(), e);
		}
		return json;
	}	
可以請求到令牌的寫法:
private static JSONObject getJsonFromUrl(String urlStr) {
		// org.apache.http.client.HttpClient
		HttpClient httpClient = new DefaultHttpClient();
		// org.apache.http.client.methods.HttpPost
		HttpPost httpPost = new HttpPost(urlStr);
		String urlResult = "";
		try {
			// org.apache.http.util.EntityUtils	;Static helpers for dealing with HttpEntitys.	;Since:4.0
			// apache提供的方法 EntityUtils.toString : Get the entity content as a String, using the provided default character set if none is found in the entity. If defaultCharset is null, the default "ISO-8859-1" is used.
			urlResult = EntityUtils.toString(httpClient.execute(httpPost).getEntity(), "UTF-8");
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("urlStr from yihaodian is : " + urlResult);

		JSONObject json = JSONObject.fromObject(urlResult);
		System.out.println("urlStr to JSONObject , JSONObject is : " + json);

		return json;
	}

具體原因,還在找

然後,又出現了如下異常:

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
	at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:352)
	at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
	at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:397)
	at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148)
	at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
	at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
	at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:573)
	at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:425)
	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
好在有網,查詢後,得到了這樣的解決方案:
/**
	* 獲取可信任https連結,以避免不受信任證書出現peer not authenticated異常
	*
	* @param base
	* @return
	*/
	public static HttpClient wrapClient(HttpClient base) {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] xcs, String string) {
				}

				public void checkServerTrusted(X509Certificate[] xcs, String string) {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx);
			ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ClientConnectionManager ccm = base.getConnectionManager();
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", ssf, 443));
			System.out.println("==[" + DateUtil.DateTime() + "]成功忽略證書有效性");
			return new DefaultHttpClient(ccm, base.getParams());
		} catch (Exception ex) {
			System.out.println("==[" + DateUtil.DateTime() + "]忽略證書有效性出現異常:" + ex.getMessage());
			ex.printStackTrace();
			return null;
		}
	}
然後,HttpClient物件,需要處理一下:
HttpClient httpClient = new DefaultHttpClient();
// 獲取可信任https連結,以避免不受信任證書出現peer not authenticated異常
httpClient = wrapClient(httpClient);

說明一下需要匯入的包,因為可能有的類重名,會造成困惑。可能並不是所有的包都有用,Eclipse劃黃線的,刪掉就好:

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;