1.设置参数,使用协议读取https
public static void paramSettings(HttpClient httpclient){
try {
//Secure Protocol implementation.
SSLContext ctx = SSLContext.getInstance("SSL");
//Implementation of a trust manager for X509 certificates
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier(){
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
public void verify(String arg0, SSLSocket arg1)
throws IOException {
// TODO Auto-generated method stub
}
public void verify(String arg0, X509Certificate arg1)
throws SSLException {
// TODO Auto-generated method stub
}
public void verify(String arg0, String[] arg1, String[] arg2)
throws SSLException {
// TODO Auto-generated method stub
} };
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,hostnameVerifier);
ClientConnectionManager ccm = httpclient.getConnectionManager();
//register https protocol in httpclient's scheme registry
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
sr.register(new Scheme("http", 80,PlainSocketFactory
.getSocketFactory()));
//set Time out
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_OUT);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2.doGet
public static String getHTTPSJsonRequest(String url, String userName,
String password) {
logger.info("HttpsUtil : getHTTPSResult start............");
String result = null;
try {
HttpClient httpclient = getHttpClient();
HttpGet httpget = new HttpGet(url);
String authString = userName + ":" + password;
String authStringEnc = new String(Base64.encode(authString
.getBytes()));
httpget.addHeader("Authorization", "Basic " + authStringEnc);
httpget.addHeader("content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
result = httpclient.execute(httpget, responseHandler);
logger.debug("HttpsUtil : getHTTPSResult;result = " + result);
// Create a response handler
httpget.releaseConnection();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("HttpsUtil : getHTTPSResult end........");
return result;
}
3.doPut
public static String putHTTPSJsonRequest(String url) {
logger.info("HttpsUtil : putHTTPSResult start............");
logger.debug("url : " + url);
String info = null;
HttpClient httpclient = getHttpClient();
HttpPut httpPut = new HttpPut(url);
try {
HttpResponse httpresponse = httpclient.execute(httpPut);
HttpEntity entity = httpresponse.getEntity();
info = EntityUtils.toString(entity, "UTF-8");
System.out.println("info = " + info);
httpPut.addHeader("content-type", "application/json");
} catch (Exception e) {
logger.debug("putData Exception url:{}", url, e);
} finally {
httpPut.releaseConnection();
}
logger.info("HttpsUtil : putHTTPSResult end........");
// return info;
return info;
}
4.doPost
public static String postHTTPSJsonRequest(String url,
Map<String, String> params) {
logger.info("HttpsUtil : postHTTPSResult start............");
logger.debug("url : " + url);
String response = null;
String info = null;
HttpClient httpclient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (params != null && params.size() > 0) {
Iterator keysIterator = params.keySet().iterator();
while (keysIterator.hasNext()) {
String key = (String) keysIterator.next();
String value = params.get(key);
nameValuePairs.add(new BasicNameValuePair(key, value));
}
}
if (nameValuePairs != null && nameValuePairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
}
HttpResponse httpresponse = httpclient.execute(httpPost);
HttpEntity entity = httpresponse.getEntity();
info = EntityUtils.toString(entity, "UTF-8");
System.out.println("info = " + info);
httpPost.addHeader("content-type", "application/json");
} catch (Exception e) {
logger.debug("putData Exception url:{}", url, e);
} finally {
httpPost.releaseConnection();
}
logger.info("HttpsUtil : postHTTPSResult end........");
return info;
}
public static HttpClient getHttpClientWithSSL(String SSLPath)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException{
HttpClient httpclient = new DefaultHttpClient();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File(SSLPath));
try {
trustStore.load(instream, "123456".toCharArray());
} finally {
instream.close();
}
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore,"123456",trustStore);
Scheme sch = new Scheme("https", socketFactory, 443);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
// httpclient.getConnectionManager().shutdown();
return httpclient;
}