1. 程式人生 > >使用HttpClient訪問其他專案的介面

使用HttpClient訪問其他專案的介面

public class HttpClientUtils {
	private final static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
	//Json格式提交資料
	@SuppressWarnings("deprecation")
	public static String jsonPostRequest(String url, Map<String, Object> param) {
    	String responseBody = null;
    	 // 建立預設的httpClient例項.    
        CloseableHttpClient httpclient = HttpClients.createDefault();     
        try {    
            //以post方式請求網頁   
            HttpPost httppost = new HttpPost(url);    
            //將引數轉為JSON格式
            Gson gson = new Gson();
            String jsonParam = gson.toJson(param);
            
            httppost.setHeader("Content-Type", "application/json;charset=UTF-8"); 
            httppost.setHeader("accept","application/json");
            //將POST引數以UTF-8編碼幷包裝成表單實體物件    
            StringEntity se = new StringEntity(jsonParam, "UTF-8");
            se.setContentType("text/json");
            httppost.setEntity(se); 
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {  
                HttpEntity entity = response.getEntity();  
                if (entity != null) {  
                    responseBody = EntityUtils.toString(entity, "UTF-8");  
                }  
            } finally {  
                response.close();  
            }  
            logger.info(responseBody);    
        }catch(Exception e){  
        	logger.error("介面請求失敗:url=" + url);  
        }finally {    
            // 當不再需要HttpClient例項時,關閉連線管理器以確保釋放所有佔用的系統資源    
            httpclient.getConnectionManager().shutdown();
        }
        return responseBody;
    }
}