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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u012843873/article/details/80679046
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;
    }
}

 

展开阅读全文

没有更多推荐了,返回首页