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


此方法只支持HTTP请求,HTTPS请求会报错!
示例如下:

    /**
     * 向指定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;
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM