1. 程式人生 > >httpClient直連呼叫post介面

httpClient直連呼叫post介面

	
  public Class ClientUtil {

	/**
	  * 介面呼叫
	  * @param url 介面地址 json 為引數 參考(gson.getInstance.toJson(new HashMap("引數名","引數值")))需要轉換     * 成json串格式的
	  */
	public static String doClient(String url,String json) {
		return doPost(url,json);
	
	
	}	
	
	/**
	 * 獲取連線
	 * @return CloseableHttpClient物件
	 */
	public CloseableHttpClient buildHttpClient(){
		CloseableHttpClient client = null;
		HttpClientBuilder build = HttpClients.custom();  
		client = build.build();  
		return client;
	}
	
	/**
	 * 進行Post請求
	 * @param url 服務地址
	 * @param json 新增json串
	 * @return String結果
	 */
	public String doPost(String url,String json){
		CloseableHttpClient httpClient = buildHttpClient();
		HttpPost httpPost = new HttpPost(url);
		String result = null;
		try {
			httpPost.setHeader("content-type", "application/json;charset=UTF-8");//
			StringEntity se = new StringEntity(json,"utf-8");
		    httpPost.setEntity(se);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}
		} catch (ClientProtocolException e) {
			//logger.error("進行模擬HTTP請求時候發生異常 ,請求地址"+url,e);
		} catch (UnsupportedEncodingException e) {
			//logger.error("進行模擬HTTP請求時候發生異常,請求地址"+url,e);
		} catch (Exception e) {
			//logger.error("進行模擬HTTP請求時候發生異常,請求地址"+url,e);
		} finally {
			// 關閉連線,釋放資源    
            try {httpClient.close();  }catch (IOException e) {e.printStackTrace(); }  
		}
		return result;
	}
}