http/https接口調用

java調用http/https接口,使用httpclient!

引入jar:commons-httpclient-3.1.0.jar

</pre>baseclient,需要調用接口的繼承此類,調用其中方法!</p><p><pre name="code" class="java">package com.yskj.rest.client.common;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.log4j.Logger;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

/**
 * 
 * @Title: BaseClient.java
 * @Package com.yskj.rest.client.common
 * @Description: TODO(調用接口的基類,提供3種調用方式)
 * @date 2015年8月14日 上午11:39:27
 * @version V1.0
 */
public class BaseClient {
	Logger log = Logger.getLogger(BaseClient.class);
	public static final String charset = "UTF-8";
	
	public static final String CONTENTTYPE_APPLICATION_JSON="application/json";
	public static final String CONTENTTYPE_APPLICATION_XML ="application/xml";
	public static final String CONTENTTYPE_MULTIPART_FORM="multipart/form-data";
	public static final String TEXTPLAIN="text/plain";
	public static final String TEXTHTML="text/html";
	
	/** 
	* @Title: PostResponse 
	* @Description: TODO https / http test,如果需要使用需要在web.xml中配置RestTemplate實體
	* @param @param url
	* @param @param map
	* @param @param mediaType
	* @param @return    
	* @return String    
	* @throws 
	*/ 
	public String PostRestTemplate(String url, Object map,
			MediaType mediaType) {
		String result = "";
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(mediaType);
		HttpEntity<Object> requestEntity = new HttpEntity<Object>(map, headers);
		RestTemplate restTemplate = new RestTemplate();
		try {
			result = restTemplate.postForObject(url, requestEntity,
					String.class);
		} catch (HttpClientErrorException e) {
			log.error("BaseClient PostResponse occur error : " + e);
			throw e;
		}
		return result;
	}

	/** 
	* @Title: PostHttps  
	* @Description: TODO https 請求
	* @param @param url
	* @param @param map
	* @param @param contenttype
	* @param @return    
	* @return String    
	* @throws 
	*/ 
	public String PostHttps(String url, JSONObject map,
			String contenttype) {
		String result = "";
		HttpClient client = new HttpClient();
		Protocol myhttps = new Protocol("https",
				new MySSLProtocolSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);
		PostMethod method = new PostMethod(url);
		RequestEntity requestEntity;
		try {
			requestEntity = new StringRequestEntity(map.toString(),
					contenttype, charset);
			method.setRequestEntity(requestEntity);
			client.executeMethod(method);
			if(method.getStatusCode()!=200){
				log.info(""+method.getStatusLine());
			}
			result = method.getResponseBodyAsString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = "error_" + e.getCause().getMessage();
			log.error("BaseClient PostHttps occur error : " + e);
		}
		// 釋放連接
		method.releaseConnection();
		return result;
	}
	/** 
	* @Title: PostHttp 
	* @Description: TODO http請求
	* @param @param url
	* @param @param map
	* @param @param contenttype
	* @param @return    
	* @return String    
	* @throws 
	*/ 
	public String PostHttp(String url,JSONObject json,
			String contenttype){
		String result = "";
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		RequestEntity requestEntity;
		try {
			requestEntity = new StringRequestEntity(json.toString(),
					contenttype, charset);
			method.setRequestEntity(requestEntity);
			client.executeMethod(method);
			if(method.getStatusCode()!=200){
				log.info(""+method.getStatusLine());
			}
			result = method.getResponseBodyAsString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result = "error_" + e.getCause().getMessage();
			log.error("BaseClient PostHttp occur error : " + e);
		}
		// 釋放連接
		method.releaseConnection();
		return result;
	}
}


https需要設置信任所有證書,也可以只信任機構簽發的證書

package com.yskj.rest.client.common;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

/**
 * @Title: MySSLProtocolSocketFactory.java
 * @Package com.yskj.rest.client
 * @Description: TODO(初始化https調用,配置參數)
 * @date 2015年8月12日 上午10:58:49
 * @version V1.0
 */
public class MySSLProtocolSocketFactory implements ProtocolSocketFactory {
	private SSLContext sslcontext = null;

	private SSLContext createSSLContext() {
		SSLContext sslcontext = null;
		try {
			sslcontext = SSLContext.getInstance("SSL");
			sslcontext.init(null,
					new TrustManager[] { new TrustAnyTrustManager() },
					new java.security.SecureRandom());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		return sslcontext;
	}

	private SSLContext getSSLContext() {
		if (this.sslcontext == null) {
			this.sslcontext = createSSLContext();
		}
		return this.sslcontext;
	}

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

	public Socket createSocket(String host, int port) throws IOException,
			UnknownHostException {
		return getSSLContext().getSocketFactory().createSocket(host, port);
	}

	public Socket createSocket(String host, int port, InetAddress clientHost,
			int clientPort) throws IOException, UnknownHostException {
		return getSSLContext().getSocketFactory().createSocket(host, port,
				clientHost, clientPort);
	}

	public Socket createSocket(String host, int port, InetAddress localAddress,
			int localPort, HttpConnectionParams params) throws IOException,
			UnknownHostException, ConnectTimeoutException {
		if (params == null) {
			throw new IllegalArgumentException("Parameters may not be null");
		}
		int timeout = params.getConnectionTimeout();
		SocketFactory socketfactory = getSSLContext().getSocketFactory();
		if (timeout == 0) {
			return socketfactory.createSocket(host, port, localAddress,
					localPort);
		} else {
			Socket socket = socketfactory.createSocket();
			SocketAddress localaddr = new InetSocketAddress(localAddress,
					localPort);
			SocketAddress remoteaddr = new InetSocketAddress(host, port);
			socket.bind(localaddr);
			socket.connect(remoteaddr, timeout);
			return socket;
		}
	}

	// 自定義私有類
	private static class TrustAnyTrustManager implements X509TrustManager {

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

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

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}
}

其次如果要使用restTemplate調用接口,需要在spring中注入
<pre name="code" class="html">	<!-- Client restTemplate-->
	<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
		<property name="messageConverters">
			<list>
				<ref bean="marshallingConverter" />
				<ref bean="jsonConverter" />
			</list>
		</property>
	</bean>






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章