向指定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