1. 程式人生 > >Java實現模擬傳送POST、GET請求

Java實現模擬傳送POST、GET請求

[java] view plain copy print?
  1. import org.apache.http.HttpEntity;  
  2. import org.apache.http.client.config.RequestConfig;  
  3. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  4. import org.apache.http.client.methods.CloseableHttpResponse;  
  5. import org.apache.http.client.methods.HttpPost;  
  6. import org.apache.http.impl.client.CloseableHttpClient;  
  7. import org.apache.http.impl.client.HttpClients;  
  8. import org.apache.http.message.BasicNameValuePair;  
  9. import org.apache.http.util.EntityUtils;  
  10. import org.apache.log4j.Logger;  
  11. import java.io.BufferedReader;  
  12. import java.io.IOException;  
  13. import
     java.io.InputStreamReader;  
  14. import java.io.OutputStreamWriter;  
  15. import java.net.HttpURLConnection;  
  16. import java.net.URL;  
  17. import java.net.URLConnection;  
  18. import java.util.List;  
  19. import java.util.Map;  
  20. publicclass HttpRequestUtils {  
  21.     privatestatic Logger logger = Logger.getLogger(HttpRequestUtils.
    class);  
  22.     privatestaticfinalint connectTimeout = 1000 * 120;    // 連線超時時間
  23.     privatestaticfinalint socketTimeout = 1000 * 180;    // 讀取資料超時時間
  24.     /** 
  25.      * 向指定 URL 傳送 POST請求 
  26.      * 
  27.      * @param strUrl        傳送請求的 URL 
  28.      * @param requestParams 請求引數,格式 name1=value1&name2=value2 
  29.      * @return 遠端資源的響應結果 
  30.      */
  31.     publicstatic String sendPost(String strUrl, String requestParams) {  
  32.         logger.info(”sendPost strUrl:” + strUrl);  
  33.         logger.info(”sendPost requestParams:” + requestParams);  
  34.         URL url = null;  
  35.         HttpURLConnection httpURLConnection = null;  
  36.         try {  
  37.             url = new URL(strUrl);  
  38.             httpURLConnection = (HttpURLConnection) url.openConnection();  
  39.             httpURLConnection.setDoOutput(true);  
  40.             httpURLConnection.setDoInput(true);  
  41.             httpURLConnection.setRequestMethod(”POST”);  
  42.             httpURLConnection.setUseCaches(false);  
  43.             httpURLConnection.setRequestProperty(”Accept”“application/json”);    // 設定接收資料的格式
  44.             httpURLConnection.setRequestProperty(”Content-Type”“application/json”);  // 設定傳送資料的格式
  45.             httpURLConnection.connect();    // 建立連線
  46.             OutputStreamWriter outputStreamWriter = new OutputStreamWriter(  
  47.                     httpURLConnection.getOutputStream(), ”UTF-8”);  
  48.             outputStreamWriter.append(requestParams);  
  49.             outputStreamWriter.flush();  
  50.             outputStreamWriter.close();  
  51.             // 使用BufferedReader輸入流來讀取URL的響應
  52.             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(  
  53.                     httpURLConnection.getInputStream(), ”utf-8”));  
  54.             StringBuffer stringBuffer = new StringBuffer();  
  55.             String strLine = ”“;  
  56.             while ((strLine = bufferedReader.readLine()) != null) {  
  57.                 stringBuffer.append(strLine);  
  58.             }  
  59.             bufferedReader.close();  
  60.             String responseParams = stringBuffer.toString();  
  61.             logger.info(”sendPost responseParams:” + responseParams);  
  62.             return responseParams;  
  63.         } catch (IOException e) {  
  64.             logger.info(”sendPost IOException:” + e.getMessage());  
  65.         } finally {  
  66.             if (httpURLConnection != null) {  
  67.                 httpURLConnection.disconnect();  
  68.             }  
  69.         }  
  70.         returnnull;  
  71.     }  
  72.     /** 
  73.      * HttpClientPost 方式,向指定 URL 傳送 POST請求 
  74.      * 
  75.      * @param strUrl        傳送請求的 URL 
  76.      * @param requestParams 請求引數 
  77.      * @return 遠端資源的響應結果 
  78.      */
  79.     publicstatic String doPost(String strUrl, List<BasicNameValuePair> requestParams) {  
  80.         logger.info(”doPost strUrl:” + strUrl);  
  81.         logger.info(”doPost requestParams:” + requestParams);  
  82.         String responseParams = ”“;  
  83.         StringBuffer stringBuffer = new StringBuffer();  
  84.         long startTime = 0, endTime = 0;  
  85.         CloseableHttpClient closeableHttpClient = HttpClients.createDefault();  
  86.         RequestConfig requestConfig = RequestConfig.custom()  
  87.                 .setConnectTimeout(connectTimeout)  
  88.                 .setSocketTimeout(socketTimeout)  
  89.                 .build();    // 設定請求和傳輸超時時間
  90.         HttpPost httpPost = new HttpPost(strUrl);  
  91.         httpPost.setConfig(requestConfig);  
  92.         HttpEntity httpEntity;  
  93.         try {  
  94.             if (requestParams != null) {  
  95.                 // 設定相關引數
  96.                 httpEntity = new UrlEncodedFormEntity(requestParams, “UTF-8”);  
  97.                 httpPost.setEntity(httpEntity);  
  98.                 logger.info(”doPost requestParams:” + EntityUtils.toString(httpEntity));  
  99.             }  
  100.             startTime = System.nanoTime();  
  101.             CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);  
  102.             int code = closeableHttpResponse.getStatusLine().getStatusCode();  
  103.             logger.info(”doPost 狀態碼:” + code);  
  104.             if (code == 200 || code == 500) {  
  105.                 try {  
  106.                     httpEntity = closeableHttpResponse.getEntity();  
  107.                     if (httpEntity != null) {  
  108.                         long length = httpEntity.getContentLength();  
  109.                         // 當返回值長度較小的時候,使用工具類讀取
  110.                         if (length != -1 && length < 2048) {  
  111.                             stringBuffer.append(EntityUtils.toString(httpEntity));  
  112.                         } else {    // 否則使用IO流來讀取
  113.                             BufferedReader bufferedReader = new BufferedReader(  
  114.                                     new InputStreamReader(httpEntity.getContent(), “UTF-8”));  
  115.                             String line;  
  116.                             while ((line = bufferedReader.readLine()) != null) {  
  117.                                 stringBuffer.append(line);  
  118.                             }  
  119.                             bufferedReader.close();  
  120.                             responseParams = stringBuffer.toString();  
  121.                         }  
  122.                         endTime = System.nanoTime();  
  123.                     }  
  124.                 } catch (Exception e) {  
  125.                     endTime = System.nanoTime();  
  126.                     logger.info(”doPost Exception(通訊錯誤):” + e.getMessage());  
  127.                 } finally {  
  128.                     closeableHttpResponse.close();  
  129.                 }  
  130.             } else {  
  131.                 endTime = System.nanoTime();  
  132.                 httpPost.abort();  
  133.                 logger.info(”doPost 錯誤請求,狀態碼:” + code);  
  134.             }  
  135.         } catch (IOException e) {  
  136.             endTime = System.nanoTime();  
  137.             logger.info(”doPost IOException:” + e.getMessage());  
  138.         } finally {  
  139.             try {  
  140.                 closeableHttpClient.close();  
  141.             } catch (IOException e) {  
  142.             }  
  143.         }  
  144.         logger.info(”doPost 用時(毫秒):” + (endTime - startTime) / 1000000L);  
  145.         logger.info(”doPost responseParams:” + responseParams);  
  146.         return responseParams;  
  147.     }  
  148.     /** 
  149.      * 向指定 URL 傳送 GET請求 
  150.      * 
  151.      * @param strUrl        傳送請求的 URL 
  152.      * @param requestParams 請求引數 
  153.      * @return 遠端資源的響應結果 
  154.      */
  155.     publicstatic String sendGet(String strUrl, String requestParams) {  
  156.         logger.info(”sendGet strUrl:” + strUrl);  
  157.         logger.info(”sendGet requestParams:” + requestParams);  
  158.         String responseParams = ”“;  
  159.         BufferedReader bufferedReader = null;  
  160.         try {  
  161.             String strRequestUrl = strUrl + ”?” + requestParams;  
  162.             URL url = new URL(strRequestUrl);  
  163.             URLConnection urlConnection = url.openConnection();    // 開啟與 URL 之間的連線
  164.             // 設定通用的請求屬性
  165.             urlConnection.setRequestProperty(”accept”“*/*”);  
  166.             urlConnection.setRequestProperty(”connection”“Keep-Alive”);  
  167.             urlConnection.setRequestProperty(”user-agent”,  
  168.                     ”Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)”);  
  169.             urlConnection.connect();    // 建立連線
  170.             Map<String, List<String>> map = urlConnection.getHeaderFields();    // 獲取所有響應頭欄位
  171.             // 使用BufferedReader輸入流來讀取URL的響應
  172.             bufferedReader = new BufferedReader(new InputStreamReader(  
  173.                     urlConnection.getInputStream()));  
  174.             String strLine;  
  175.             while ((strLine = bufferedReader.readLine()) != null) {  
  176.                 responseParams += strLine;  
  177.             }  
  178.         } catch (Exception e) {  
  179.             logger.info(”sendGet Exception:” + e.getMessage());  
  180.         } finally {  
  181.             try {  
  182.                 if (bufferedReader != null) {  
  183.                     bufferedReader.close();  
  184.                 }  
  185.             } catch (Exception e2) {  
  186.                 e2.printStackTrace();  
  187.             }  
  188.         }  
  189.         logger.info(”sendPost responseParams:” + responseParams);  
  190.         return responseParams;  
  191.     }  
  192. }  
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpRequestUtils {

    private static Logger logger = Logger.getLogger(HttpRequestUtils.class);

    private static final int connectTimeout = 1000 * 120;    // 連線超時時間
    private static final int socketTimeout = 1000 * 180;    // 讀取資料超時時間

    /**
     * 向指定 URL 傳送 POST請求
     *
     * @param strUrl        傳送請求的 URL
     * @param requestParams 請求引數,格式 name1=value1&name2=value2
     * @return 遠端資源的響應結果
     */
    public static String sendPost(String strUrl, String requestParams) {
        logger.info("sendPost strUrl:" + strUrl);
        logger.info("sendPost requestParams:" + requestParams);

        URL url = null;
        HttpURLConnection httpURLConnection = null;
        try {
            url = new URL(strUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestProperty("Accept", "application/json");    // 設定接收資料的格式
            httpURLConnection.setRequestProperty("Content-Type", "application/json");  // 設定傳送資料的格式
            httpURLConnection.connect();    // 建立連線
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                    httpURLConnection.getOutputStream(), "UTF-8");
            outputStreamWriter.append(requestParams);
            outputStreamWriter.flush();
            outputStreamWriter.close();

            // 使用BufferedReader輸入流來讀取URL的響應
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    httpURLConnection.getInputStream(), "utf-8"));
            StringBuffer stringBuffer = new StringBuffer();
            String strLine = "";
            while ((strLine = bufferedReader.readLine()) != null) {
                stringBuffer.append(strLine);
            }
            bufferedReader.close();
            String responseParams = stringBuffer.toString();

            logger.info("sendPost responseParams:" + responseParams);

            return responseParams;
        } catch (IOException e) {
            logger.info("sendPost IOException:" + e.getMessage());
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }

        return null;
    }

    /**
     * HttpClientPost 方式,向指定 URL 傳送 POST請求
     *
     * @param strUrl        傳送請求的 URL
     * @param requestParams 請求引數
     * @return 遠端資源的響應結果
     */
    public static String doPost(String strUrl, List<BasicNameValuePair> requestParams) {
        logger.info("doPost strUrl:" + strUrl);
        logger.info("doPost requestParams:" + requestParams);

        String responseParams = "";
        StringBuffer stringBuffer = new StringBuffer();
        long startTime = 0, endTime = 0;

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout)
                .setSocketTimeout(socketTimeout)
                .build();    // 設定請求和傳輸超時時間

        HttpPost httpPost = new HttpPost(strUrl);
        httpPost.setConfig(requestConfig);
        HttpEntity httpEntity;

        try {
            if (requestParams != null) {
                // 設定相關引數
                httpEntity = new UrlEncodedFormEntity(requestParams, "UTF-8");
                httpPost.setEntity(httpEntity);

                logger.info("doPost requestParams:" + EntityUtils.toString(httpEntity));
            }
            startTime = System.nanoTime();
            CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
            int code = closeableHttpResponse.getStatusLine().getStatusCode();

            logger.info("doPost 狀態碼:" + code);

            if (code == 200 || code == 500) {
                try {
                    httpEntity = closeableHttpResponse.getEntity();
                    if (httpEntity != null) {
                        long length = httpEntity.getContentLength();
                        // 當返回值長度較小的時候,使用工具類讀取
                        if (length != -1 && length < 2048) {
                            stringBuffer.append(EntityUtils.toString(httpEntity));
                        } else {    // 否則使用IO流來讀取
                            BufferedReader bufferedReader = new BufferedReader(
                                    new InputStreamReader(httpEntity.getContent(), "UTF-8"));
                            String line;
                            while ((line = bufferedReader.readLine()) != null) {
                                stringBuffer.append(line);
                            }
                            bufferedReader.close();
                            responseParams = stringBuffer.toString();
                        }
                        endTime = System.nanoTime();
                    }
                } catch (Exception e) {
                    endTime = System.nanoTime();

                    logger.info("doPost Exception(通訊錯誤):" + e.getMessage());
                } finally {
                    closeableHttpResponse.close();
                }
            } else {
                endTime = System.nanoTime();
                httpPost.abort();

                logger.info("doPost 錯誤請求,狀態碼:" + code);
            }
        } catch (IOException e) {
            endTime = System.nanoTime();

            logger.info("doPost IOException:" + e.getMessage());
        } finally {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
            }
        }

        logger.info("doPost 用時(毫秒):" + (endTime - startTime) / 1000000L);
        logger.info("doPost responseParams:" + responseParams);

        return responseParams;
    }

    /**
     * 向指定 URL 傳送 GET請求
     *
     * @param strUrl        傳送請求的 URL
     * @param requestParams 請求引數
     * @return 遠端資源的響應結果
     */
    public static String sendGet(String strUrl, String requestParams) {
        logger.info("sendGet strUrl:" + strUrl);
        logger.info("sendGet requestParams:" + requestParams);

        String responseParams = "";
        BufferedReader bufferedReader = null;
        try {
            String strRequestUrl = strUrl + "?" + requestParams;
            URL url = new URL(strRequestUrl);
            URLConnection urlConnection = url.openConnection();    // 開啟與 URL 之間的連線

            // 設定通用的請求屬性
            urlConnection.setRequestProperty("accept", "*/*");
            urlConnection.setRequestProperty("connection", "Keep-Alive");
            urlConnection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            urlConnection.connect();    // 建立連線

            Map<String, List<String>> map = urlConnection.getHeaderFields();    // 獲取所有響應頭欄位

            // 使用BufferedReader輸入流來讀取URL的響應
            bufferedReader = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));
            String strLine;
            while ((strLine = bufferedReader.readLine()) != null) {
                responseParams += strLine;
            }
        } catch (Exception e) {
            logger.info("sendGet Exception:" + e.getMessage());
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        logger.info("sendPost responseParams:" + responseParams);

        return responseParams;
    }
}