1. 程式人生 > >HTTP POST方法呼叫

HTTP POST方法呼叫

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;




/**
 * <p>
 * Description: HTTP 協議的客戶端工具包   暫不支援https
 * </p>
 *
 * 使用HttpClient傳送請求、接收響應很簡單,一般需要如下幾步即可。
 * 建立HttpClient物件。
 * 建立請求方法的例項,並指定請求URL。如果需要傳送GET請求,建立HttpGet物件;如果需要傳送POST請求,建立HttpPost物件。
 * 如果需要傳送請求引數,可呼叫HttpGet、HttpPost共同的setParams(HetpParams params)方法來新增請求引數;對於HttpPost物件而言,也可呼叫setEntity(HttpEntity entity)方法來設定請求引數。
 * 呼叫HttpClient物件的execute(HttpUriRequest request)傳送請求,該方法返回一個HttpResponse。
 * 呼叫HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取伺服器的響應頭;呼叫HttpResponse的getEntity()方法可獲取HttpEntity物件,該物件包裝了伺服器的響應內容。程式可通過該物件獲取伺服器的響應內容。
 * 釋放連線。無論執行方法是否成功,都必須釋放連線
 */
public class HttpClientUtil {
	
	private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
	public static final String CONTENT_CHARSET = "utf-8";
	public static final String CONTENT_TYPE1 = "application/x-www-form-urlencoded";
	public static final String CONTENT_TYPE2 = "application/json";
	
	/**
	 * 使用HTTP POST方法向指定URL提交資料
	 *
	 * @param url
	 * @param params
	 * @return
	 * @throws ApiCheckedException
	 * @author 80002016
	 * @throws ErrorException 
	 */
	public static String post(final String url, final Map<String, String> params) throws ErrorException {
		String responseStr = null;
		try {
			//建立客戶端(HttpClient)的例項
			HttpClient httpclient = new DefaultHttpClient();
			httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);//設定連線時間5秒
			
			HttpPost post = createHttpPost(url, params);
			// 提交post請求,並返回一個HttpResponse物件
			HttpResponse httpResponse = httpclient.execute(post);
			// 解析返回資料
			responseStr = parseResponse(httpResponse);
			
			//無論執行方法是否成功,都必須釋放連線
			httpclient.getConnectionManager().shutdown();
			
		} catch (Exception e) {
			log.error("ACSP-E-BILL處理http post請求發生異常,url:{},params:{},exception:{}", url, params, e);
			throw new ErrorException("ACSP-E-BILL處理http post請求發生異常"+e.getMessage());
		}
		return responseStr;
	}
	
	public static String post2(final String url, final Map<String, Object> params) throws ErrorException  {
		String responseStr = null;
		try {
			//建立客戶端(HttpClient)的例項
			HttpClient httpclient = new DefaultHttpClient();
			httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);//設定連線時間5秒
			
			HttpPost post = createHttpPost2(url, params);
			// 提交post請求,並返回一個HttpResponse物件
			HttpResponse httpResponse = httpclient.execute(post);
			// 解析返回資料
			responseStr = parseResponse(httpResponse);
			
			//無論執行方法是否成功,都必須釋放連線
			httpclient.getConnectionManager().shutdown();
			
		} catch (Exception e) {
			log.error("ACSP-E-BILL處理http post請求發生異常,url:{},params:{},exception:{}", url, params, e);
			throw new ErrorException("ACSP-E-BILL處理http post請求發生異常"+e.getMessage());
		}
		return responseStr;
	}
	public static String post(String url,String params) throws ErrorException {
		String responseStr = null;
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			
			httpPost.addHeader(new BasicHeader(HTTP.CONTENT_TYPE, Constants.contentType.CONTENT_TYPE2));
			httpPost.setEntity(new StringEntity(params));
	
			HttpResponse response = httpclient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				throw new ErrorException(String.valueOf(statusCode));
			}
			HttpEntity entity = response.getEntity();
			responseStr = EntityUtils.toString(entity, Constants.contentType.CONTENT_CHARSET);
			
		}catch(Exception e){
			log.error("ACSP-E-BILL處理http post請求發生異常,url:{},params:{},exception:{}", url, params, e);
			throw new ErrorException("ACSP-E-BILL處理http post請求發生異常"+e.getMessage());
		}
		return responseStr;
		
	}
	/**
	 * 建立HttpPost物件請求方法的例項
	 *
	 * @param url
	 * @param params
	 * @return HttpPost物件
	 * @throws ApiCheckedException
	 * @throws ErrorException 
	 */
	private static HttpPost createHttpPost(final String url, final Map<String, String> params) throws ErrorException  {
		HttpPost httpost = new HttpPost(url);
		
		//視業務情況是否需要copyHeader
		HttpServletRequest request = SpringUtil.getRequest();
		if (request != null) {// 從系統內部請求,不經過controller
			copyHeader(httpost, request);
		}
		Set<String> keySet = params.keySet();
		/*List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (String key : keySet) {
			nvps.add(new BasicNameValuePair(key, params.get(key)));
		}*/
		JSONObject json = new JSONObject();  
		for (String key : keySet) {
			json.put(key, params.get(key));
		}
		
		try {
			//設定請求引數
			StringEntity s = new StringEntity(json.toJSONString(), Constants.contentType.CONTENT_CHARSET);    
//          s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, Constants.contentType.CONTENT_TYPE2));
            httpost.setEntity(s);
//            httpost.setEntity(new UrlEncodedFormEntity(nvps, Constants.DEFAULT_CHARSET));
		} catch (UnsupportedEncodingException e) {
			log.error("createHttpPost====字元編碼格式不支援:",e);
			throw new ErrorException("字元編碼格式不支援"+e.getMessage());
		}
		return httpost;
	}
	
	private static HttpPost createHttpPost2(final String url, final Map<String, Object> params) throws ErrorException {
		HttpPost httpost = new HttpPost(url);
		
		//視業務情況是否需要copyHeader
		HttpServletRequest request = SpringUtil.getRequest();
		if (request != null) {// 從系統內部請求,不經過controller
			copyHeader(httpost, request);
		}
		Set<String> keySet = params.keySet();
		/*List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (String key : keySet) {
			nvps.add(new BasicNameValuePair(key, params.get(key)));
		}*/
		JSONObject json = new JSONObject();  
		for (String key : keySet) {
			json.put(key, params.get(key));
		}
		
		try {
			//設定請求引數
			StringEntity s = new StringEntity(json.toJSONString(), Constants.contentType.CONTENT_CHARSET);    
//          s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, Constants.contentType.CONTENT_TYPE2));
            httpost.setEntity(s);
//            httpost.setEntity(new UrlEncodedFormEntity(nvps, Constants.DEFAULT_CHARSET));
		} catch (UnsupportedEncodingException e) {
			log.error("createHttpPost2====字元編碼格式不支援:",e);
			throw new ErrorException("字元編碼格式不支援"+e.getMessage());
		}
		return httpost;
	}
	
	
	/**
	 * 解析HttpResponse  讀取伺服器反饋回來的結果
	 *
	 * @param response
	 * @param charSet
	 * @return response字串
	 * @throws ApiCheckedException
	 * @throws ErrorException 
	 */
	private static String parseResponse(final HttpResponse response) throws ErrorException {
		if (response == null) {
			return null;
		}
		HttpEntity entity = response.getEntity();
		String body = null;
		try {
			body = EntityUtils.toString(entity, Constants.contentType.CONTENT_CHARSET);
		} catch (ParseException e) {
			log.error("parseResponse====解析response出錯:",e);
			throw new ErrorException("解析response出錯"+e.getMessage());
		} catch (IOException e) {
			log.error("parseResponse====傳送http報文時,IO異常:",e);
			throw new ErrorException("傳送http報文時,IO異常"+e.getMessage());
		}
		log.info("XX介面 result:" + body);
		return body;
	}
	
	/**
	 * 複製頭資訊
	 *
	 * @param httpost
	 * @param request
	 * @author 80002016
	 */
	private static void copyHeader(final HttpPost httpost, final HttpServletRequest request) {
		httpost.addHeader("tokenId", request.getHeader("tokenId"));
		httpost.addHeader("region_code", request.getHeader("region_code"));
		httpost.addHeader("language_code", request.getHeader("language_code"));
		httpost.addHeader("screen_size", request.getHeader("screen_size"));
		httpost.addHeader("platform", request.getHeader("platform"));
		httpost.addHeader("protocol_ver", request.getHeader("protocol_ver"));
		httpost.addHeader("model", request.getHeader("model"));
		httpost.addHeader("carrier", request.getHeader("carrier"));
		httpost.addHeader("client_ver", request.getHeader("client_ver"));
		httpost.addHeader("cookie", request.getHeader("cookie"));
		httpost.addHeader("systemVersion", request.getHeader("systemVersion"));
//		httpost.addHeader("langCode", request.getHeader("langCode"));
		
		
		/*@SuppressWarnings("unchecked")
		Enumeration<String> headers = request.getHeaderNames(); // 通過列舉型別獲取請求檔案的頭部資訊集
		// 遍歷頭部資訊集
		while (headers.hasMoreElements()) {
			// 取出資訊名
			String name = (String) headers.nextElement();
			// 取出資訊值
			String value = request.getHeader(name);
			httpost.addHeader(name, value);
		}*/
	}
}
/**
 * 自定義異常類
 *
 */
public class ErrorException  extends RuntimeException {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4379876817711661340L;

	public ErrorException(String msg)
	 {
	   super(msg);
	 }
	public ErrorException(String string, Exception e) {
		super(string, e);
	}

}