apache http get 和 post 請求


1、首先要把jar依賴進項目

<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.3</version>
</dependency>

2、get/post方法

/**
     * http post 請求
     * 1、創建 client 實例
     * 2、創建 post 實例
     * 3、設置 post 參數
     * 4、發送請求
     */
    public static String post(String url, Map<String, String> params) {
        if (url == null) {
            LOGGER.info("http url can not be empty!");
        }
        String respCtn = "";
        // 1、創建 client 實例
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 2、創建 post 實例
        HttpPost post = new HttpPost(url);
        
        ArrayList<NameValuePair> reqParams = null;
        if (params != null && !params.isEmpty()) {
            reqParams = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> e : params.entrySet()) {
                reqParams.add(new BasicNameValuePair(e.getKey(), e.getValue()));
            }
        }

        HttpResponse response = null;
        try {
            if (reqParams != null)
                // 3、設置 post 參數
                post.setEntity(new UrlEncodedFormEntity(reqParams, "UTF-8"));
            // 4、發送請求
            response = httpclient.execute(post);
            respCtn = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            LOGGER.error("Fail to connect to remote host [" + url + "]" + e);
        } finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                }
            }
        }
        return respCtn;
    }

/**
     * http get 請求
     * 
     * @param String
     *            url
     * 
     */
    public static String doGet(String url) {
        if (url == null || url.isEmpty()) {
            LOGGER.info("http url can not be empty!");
        }
        String respCtn = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpResponse response = null;
            HttpGet get = new HttpGet(url);
            response = httpclient.execute(get);
            respCtn = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                }
            }
        }
        return respCtn;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM