javaweb后台发起http请求

直接上代码

public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                        // 将内容放请求对象中
            httpPost.setEntity(entity);
                        // 执行http请求
            response = httpClient.execute(httpPost);
            if(response != null && response.getEntity() != null) {
      //设置响应返回的编码格式及转字符串
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }else{
                resultString = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("http请求失败:", e);
            }
        }
        return resultString;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容