使用HttpClient访问其他项目的接口

public class HttpClientUtils {
	private final static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
	//Json格式提交数据
	@SuppressWarnings("deprecation")
	public static String jsonPostRequest(String url, Map 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;
    }
}

 

你可能感兴趣的:(Java)