美文网首页
javaweb后台发起http请求

javaweb后台发起http请求

作者: 乡村码农 | 来源:发表于2022-01-24 11:21 被阅读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;
    }

相关文章

网友评论

      本文标题:javaweb后台发起http请求

      本文链接:https://www.haomeiwen.com/subject/evlbhrtx.html