1. 程式人生 > >apache httpclient HTTPS傳送JSON呼叫介面例項

apache httpclient HTTPS傳送JSON呼叫介面例項

1.目的:呼叫第三方介面

2.協議:https

3.報文格式:JSON

4.依賴jar如下

		<!-- httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.5</version>
		</dependency>

		<!-- jsckson -->
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-databind</artifactId>
		    <version>2.9.4</version>
		</dependency>
5.相關程式碼

1). action類

package com.koon.demo1;

import com.fasterxml.jackson.core.JsonProcessingException;

public class XinYongCardAction {

	public static void main(String[] args) throws JsonProcessingException {
		
		//uri
		String uri = "https://x.xxx.com/xxx/getToken";
		
		String mess = new AssemblingMessTool().getMess();
		
		String returnMess = new HttpsSendMessTool().postReturnMess(uri, mess);
		
		System.out.println(returnMess);
	}
}

2). 傳送報文工具類

package com.koon.demo1;

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.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpsSendMessTool {
	
	public String getReturnMess(String uri) {
		
		String returnMess = "";

		CloseableHttpClient httpClient = null;
		HttpGet httpGet = null;
		
		try {
			
			httpClient = (CloseableHttpClient) wrapClient();
			
			httpGet = new HttpGet(uri);
			
			CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
			
			HttpEntity httpEntity = httpResponse.getEntity();
			
			returnMess = EntityUtils.toString(httpEntity, "utf-8");
		} catch (Exception e) {

			e.printStackTrace();
		}
		
		return returnMess;
	}
	
	public String postReturnMess(String uri, String jsonMess) {
		
		String returnMess = "";
		
		CloseableHttpClient httpClient = null;
		HttpPost httpPost;
		
		try {
			
			httpClient = (CloseableHttpClient) wrapClient();
			
			httpPost = new HttpPost(uri);

			StringEntity entity = new StringEntity(jsonMess);
			
			httpPost.setEntity(entity);
			
			CloseableHttpResponse response = httpClient.execute(httpPost);
			
			HttpEntity resEntity = response.getEntity();
			
			returnMess = EntityUtils.toString(resEntity, "utf-8");
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
		return returnMess;
	}
	
	public static HttpClient wrapClient() {
		
		try {
			
			SSLContext context = SSLContext.getInstance("SSL");
			
			X509TrustManager manager = new X509TrustManager() {
				
				@Override
				public X509Certificate[] getAcceptedIssuers() {
					// TODO Auto-generated method stub
					return null;
				}
				
				@Override
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					// TODO Auto-generated method stub
					
				}
			};
			
			context.init(null, new TrustManager[] { manager }, null);
			
			SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context,
					NoopHostnameVerifier.INSTANCE);
			
			CloseableHttpClient httpClient = HttpClients.custom()
					.setSSLContext(context).build();
			
			return httpClient;
		} catch (Exception e) {
			
			System.out.println(123);
			return HttpClients.createDefault();
		}
	}
}

3). JSON工具類

package com.koon.demo1;

import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonTool {

	public String getJson(Map<String, Object> mess) {
		
		String result = "";
		
		ObjectMapper mapper = new ObjectMapper();
		
		try {
			
			result = mapper.writeValueAsString(mess);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
		return result;
	}
}
4). 拼裝訊息物件類
package com.koon.demo1;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

public class AssemblingMessTool {

	private String timestamp;
	private String appKey;
	private String sign;

	public AssemblingMessTool() {

		this.timestamp = System.currentTimeMillis() + "";
		this.appKey = "key";

		String tmp = "appKey=" + this.appKey + "×tamp" + this.timestamp + "&appSecret=192006250b4c09247ec02edce69f6a2d";
		this.sign = MD5(tmp).toUpperCase();
	}
	
	public String getMess() {
		
		Map<String, Object> parent = new HashMap<>();
		Map<String, Object> son = new HashMap<>();
		
		son.put("appKey", this.appKey);
		son.put("timestamp", this.timestamp);
		
		parent.put("sign", this.sign);
		parent.put("params", son);
		
		return new JsonTool().getJson(parent);
	}

	private String MD5(String s) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] bytes = md.digest(s.getBytes("utf-8"));
			return toHex(bytes);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static String toHex(byte[] bytes) {

		final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
		StringBuilder ret = new StringBuilder(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
			ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
		}
		return ret.toString();
	}

	public String getTimeStamp() {
		return timestamp;
	}

	public void setTimeStamp(String timeStamp) {
		this.timestamp = timeStamp;
	}

	public String getAppKey() {
		return appKey;
	}

	public void setAppKey(String appKey) {
		this.appKey = appKey;
	}

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

}