1. 程式人生 > >HttpClient 傳送 POST 請求

HttpClient 傳送 POST 請求

##API 說明
HttpClientBuilder用於建立CloseableHttpClient例項。
在 HttpClient 新的版本中, AbstractHttpClient、 AutoRetryHttpClient、 DefaultHttpClient等都被棄用了,使用HttpClientBuilder代替。

##Client 程式碼

package com.bilfinance.core.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.achievo.framework.exception.FrameworkException;
import com.bilfinance.core.model.AsParam;
import com.bilfinance.core.model.AsResult;
import com.bilfinance.core.service.IAsHttpInterficeService;

@Service
public class AsHttpInterficeService implements IAsHttpInterficeService {

	private static Logger logger = LoggerFactory.getLogger(AsHttpInterficeService.class);


	@Override
	public AsResult doAsHttpMethod(AsParam asParam) throws FrameworkException {
		//請求內容
		String content = JSONObject.fromObject((Object)asParam).toString();
		logger.debug("AsParam = "+content);
		byte[] byte_content = null;
		try {
			byte_content = content.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e2) {
			throw new FrameworkException("請求引數字符集編碼異常:Charset=UTF-8");
		}
		
		//建立連線
		String urlstr = "http://localhost:7070/bqjrcar/WeiXinServlet";
		logger.debug("URL = "+urlstr);
		CloseableHttpClient client = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(urlstr);
		post.setConfig(RequestConfig.DEFAULT);
		EntityBuilder enbu = EntityBuilder.create().setContentType(ContentType.APPLICATION_JSON).setContentEncoding("UTF-8").setBinary(byte_content);
		HttpEntity rqEntity = enbu.build();
		post.setEntity(rqEntity);
		
		//執行請求
		HttpResponse httprs = null;
		try {
			httprs = client.execute(post);
		} catch (IOException e) {
			throw new FrameworkException("請求失敗。meg="+e.getMessage(),e);
		}
		HttpEntity rsEntity = httprs.getEntity();
		logger.debug("StatusLine = "+httprs.getStatusLine());
		
		//返回結果
		AsResult result = null;
		if(httprs.getStatusLine().getStatusCode() != 200)
			throw new FrameworkException("安碩系統異常,StatusLine="+httprs.getStatusLine());
		if(rsEntity==null) 
			throw new FrameworkException("安碩儲存返回空");
		try {
			String text = EntityUtils.toString(rsEntity, "UTF-8");
			logger.debug("AsResult = "+text);
			result = (AsResult)JSONObject.toBean(JSONObject.fromObject(text), AsResult.class);
		} catch (ParseException | IOException e) {
			throw new FrameworkException("安碩返回字符集編碼異常:Charset=UTF-8");
		}
		
		//關閉連線
		try {
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	

}

##Servlet 程式碼

package com.weixinservlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.amarsoft.are.ARE;

import net.sf.json.JSONObject;

public class WeiXinServlet extends HttpServlet{

	private static final long serialVersionUID = -3501685878733962236L;
	
	
	@Override
	protected void service(HttpServletRequest rq, HttpServletResponse rs) throws ServletException, IOException {
		AsParam param = getPostParameter(rq);
		AsResult result = new AsResult();
		
		//合同儲存
		if(AsParam.method_saveBC.equals(param.getMethod())){
			try {
				result = new WeiXinSaveCreditInfo().saveCreditInfo(param);
				result.setStatus(AsResult.status_success);
			} catch (Exception e) {
				result.setStatus(AsResult.status_failed);
				result.setMessage(e.getMessage());
			}
		}else {
			result.setStatus(AsResult.status_failed);
			result.setMessage("方法名稱不正確,method="+param.getMethod());
		}
		
		//設定 Response
		rs.setContentType("text/html; charset=utf-8");
		rs.setCharacterEncoding("UTF-8");
		String asResult = JSONObject.fromObject(result).toString();
		ARE.getLog().debug("AsResult = "+asResult);
		rs.getWriter().println(asResult);
	}
	
	
	/**
	 * 獲取request引數
	 */
	private AsParam getPostParameter(HttpServletRequest request){
		StringBuffer sb = new StringBuffer();
		try {
			InputStream in = request.getInputStream();
			BufferedReader breader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
			String strTem;
			while((strTem=breader.readLine())!=null)
				sb.append(strTem); 
			breader.close();
			
			ARE.getLog().debug("AsParam = "+sb.toString());
			JSONObject datas = JSONObject.fromObject(sb.toString());
			AsParam bean = (AsParam)JSONObject.toBean(datas, AsParam.class);
			return bean;
		} catch (Exception e) {
			throw new RuntimeException("引數JSON格式錯誤!request="+sb.toString(),e);
		}
	}
}

##AsParam.java

package com.weixinservlet;

import java.io.Serializable;
import java.util.HashMap;

public class AsParam implements Serializable{
	
	private static final long serialVersionUID = 1063546577762134098L;
	public static final String method_saveBC = "SaveCreditInfo"; 
	private String method;
	private String message;
	private HashMap<String, Object> data;
	public String getMethod() {
		return method;
	}
	public void setMethod(String method) {
		this.method = method;
	}
	public HashMap<String, Object> getData() {
		return data;
	}
	public void setData(HashMap<String, Object> data) {
		this.data = data;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}

}

##AsResult.java

package com.weixinservlet;

import java.io.Serializable;
import java.util.HashMap;

public class AsResult implements Serializable{
	
	private static final long serialVersionUID = -6044201397210634459L;
	public static final String status_success = "SUCCESS";
	public static final String status_failed = "FAILED";
	
	private String status;
	private String message;
	private HashMap<String, Object> data;
	
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public HashMap<String, Object> getData() {
		return data;
	}
	public void setData(HashMap<String, Object> data) {
		this.data = data;
	}

}