javaweb后台发起http请求

2022-01-24  本文已影响0人  乡村码农

直接上代码

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;
    }
上一篇 下一篇

猜你喜欢

热点阅读