其他分享
首页 > 其他分享> > 向指定URL发送POST请求的方法

向指定URL发送POST请求的方法

作者:互联网

示例如下:

    /**
     * 向指定URL发送POST请求,格式为JSON
     * @param url
     * @param jsonStr
     * @return
     * @throws Exception
     */
public static String sendHttpPost(String url, String jsonStr) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(jsonStr));

        CloseableHttpResponse response = httpClient.execute(httpPost);
        System.out.println(response.getStatusLine().getStatusCode() + "\n");
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8");
        System.out.println("loginResultJson:" + responseContent);

        response.close();
        httpClient.close();
        return responseContent;
    }

标签:jsonStr,String,responseContent,URL,发送,httpPost,POST,response,httpClient
来源: https://www.cnblogs.com/xiaolibiji/p/15783123.html