JAVA HTTPS

因爲微信需要使用到https請求,所以貼下代碼:

需要引入包下載地址:點擊打開鏈接

需要寫一個類,代碼如下:

package com.dc.test;

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.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;

public class SSLSocketFactoryEx extends org.apache.http.conn.ssl.SSLSocketFactory
{
  SSLContext sslContext = SSLContext.getInstance("TLS");

  public SSLSocketFactoryEx(KeyStore truststore)
    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException
  {
    super(truststore);

    TrustManager tm = new X509TrustManager()
    {
      public X509Certificate[] getAcceptedIssuers()
      {
        return null;
      }

      public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException
      {
      }

      public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException
      {
      }
    };
    this.sslContext.init(null, new TrustManager[] { tm }, null);
  }

  public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
    throws IOException, UnknownHostException
  {
    return this.sslContext.getSocketFactory().createSocket(socket, host, port, 
      autoClose);
  }

  public Socket createSocket()
    throws IOException
  {
    return this.sslContext.getSocketFactory().createSocket();
  }

  public static HttpClient getNewHttpClient()
  {
    try
    {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);

      org.apache.http.conn.ssl.SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
      sf.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

      HttpParams params = new BasicHttpParams();
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, "UTF-8");

      SchemeRegistry registry = new SchemeRegistry();
      registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      registry.register(new Scheme("https", sf, 443));

      ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

      return new DefaultHttpClient(ccm, params); } catch (Exception e) {
    }
    return new DefaultHttpClient();
  }
}

https代碼:

/**
	 * HTTPS GET
	 * 
	 * @param url
	 */
	public static void httpsGet(String url) {
		try {
			HttpClient httpclient = SSLSocketFactoryEx.getNewHttpClient();
			HttpGet request = new HttpGet(url);
			HttpResponse response = httpclient.execute(request);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String content = IOUtils.toString(entity.getContent(), "UTF-8");
				JSONObject jo = new JSONObject(content);
				String test = jo.getString("test"); // 使用json對象獲取返回的值
				System.out.println(test);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * HTTPS POST
	 * @param url
	 */
	public static void httpsPost(String url) {
		try {
			org.apache.http.client.HttpClient httpclient = SSLSocketFactoryEx
					.getNewHttpClient();
			HttpPost post = new HttpPost(url);

			// 發送的消息體是json格式的可以這樣寫
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("component_appid", "");
			jsonObj.put("component_appsecret", "");
			jsonObj.put("component_verify_ticket", "");
			post.setEntity(new StringEntity(jsonObj.toString()));
			
			HttpResponse response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String content = IOUtils.toString(entity.getContent(), "UTF-8");
				System.out.println("content: " + content);
				JSONObject jo = new JSONObject(content); 
				String test = jo.getString("test"); // 使用json對象獲取返回的值
				System.out.println(test);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}




發佈了77 篇原創文章 · 獲贊 51 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章