Java实现模拟发送POST、GET请求

——————————————————————————————————

  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.   
  12. import java.io.BufferedReader;  
  13. import java.io.IOException;  
  14. import java.io.InputStreamReader;  
  15. import java.io.OutputStreamWriter;  
  16. import java.net.HttpURLConnection;  
  17. import java.net.URL;  
  18. import java.net.URLConnection;  
  19. import java.util.List;  
  20. import java.util.Map;  
  21.   
  22. public class HttpRequestUtils {  
  23.   
  24.     private static Logger logger = Logger.getLogger(HttpRequestUtils.class);  
  25.   
  26.     private static final int connectTimeout = 1000 * 120;    // 连接超时时间  
  27.     private static final int socketTimeout = 1000 * 180;    // 读取数据超时时间  
  28.   
  29.     /** 
  30.      * 向指定 URL 发送 POST请求 
  31.      * 
  32.      * @param strUrl        发送请求的 URL 
  33.      * @param requestParams 请求参数,格式 name1=value1&name2=value2 
  34.      * @return 远程资源的响应结果 
  35.      */  
  36.     public static String sendPost(String strUrl, String requestParams) {  
  37.         logger.info(”sendPost strUrl:” + strUrl);  
  38.         logger.info(”sendPost requestParams:” + requestParams);  
  39.   
  40.         URL url = null;  
  41.         HttpURLConnection httpURLConnection = null;  
  42.         try {  
  43.             url = new URL(strUrl);  
  44.             httpURLConnection = (HttpURLConnection) url.openConnection();  
  45.             httpURLConnection.setDoOutput(true);  
  46.             httpURLConnection.setDoInput(true);  
  47.             httpURLConnection.setRequestMethod(”POST”);  
  48.             httpURLConnection.setUseCaches(false);  
  49.             httpURLConnection.setRequestProperty(”Accept”“application/json”);    // 设置接收数据的格式  
  50.             httpURLConnection.setRequestProperty(”Content-Type”“application/json”);  // 设置发送数据的格式  
  51.             httpURLConnection.connect();    // 建立连接  
  52.             OutputStreamWriter outputStreamWriter = new OutputStreamWriter(  
  53.                     httpURLConnection.getOutputStream(), ”UTF-8”);  
  54.             outputStreamWriter.append(requestParams);  
  55.             outputStreamWriter.flush();  
  56.             outputStreamWriter.close();  
  57.   
  58.             // 使用BufferedReader输入流来读取URL的响应  
  59.             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(  
  60.                     httpURLConnection.getInputStream(), ”utf-8”));  
  61.             StringBuffer stringBuffer = new StringBuffer();  
  62.             String strLine = ”“;  
  63.             while ((strLine = bufferedReader.readLine()) != null) {  
  64.                 stringBuffer.append(strLine);  
  65.             }  
  66.             bufferedReader.close();  
  67.             String responseParams = stringBuffer.toString();  
  68.   
  69.             logger.info(”sendPost responseParams:” + responseParams);  
  70.   
  71.             return responseParams;  
  72.         } catch (IOException e) {  
  73.             logger.info(”sendPost IOException:” + e.getMessage());  
  74.         } finally {  
  75.             if (httpURLConnection != null) {  
  76.                 httpURLConnection.disconnect();  
  77.             }  
  78.         }  
  79.   
  80.         return null;  
  81.     }  
  82.   
  83.     /** 
  84.      * HttpClientPost 方式,向指定 URL 发送 POST请求 
  85.      * 
  86.      * @param strUrl        发送请求的 URL 
  87.      * @param requestParams 请求参数 
  88.      * @return 远程资源的响应结果 
  89.      */  
  90.     public static String doPost(String strUrl, List<BasicNameValuePair> requestParams) {  
  91.         logger.info(”doPost strUrl:” + strUrl);  
  92.         logger.info(”doPost requestParams:” + requestParams);  
  93.   
  94.         String responseParams = ”“;  
  95.         StringBuffer stringBuffer = new StringBuffer();  
  96.         long startTime = 0, endTime = 0;  
  97.   
  98.         CloseableHttpClient closeableHttpClient = HttpClients.createDefault();  
  99.   
  100.         RequestConfig requestConfig = RequestConfig.custom()  
  101.                 .setConnectTimeout(connectTimeout)  
  102.                 .setSocketTimeout(socketTimeout)  
  103.                 .build();    // 设置请求和传输超时时间  
  104.   
  105.         HttpPost httpPost = new HttpPost(strUrl);  
  106.         httpPost.setConfig(requestConfig);  
  107.         HttpEntity httpEntity;  
  108.   
  109.         try {  
  110.             if (requestParams != null) {  
  111.                 // 设置相关参数  
  112.                 httpEntity = new UrlEncodedFormEntity(requestParams, “UTF-8”);  
  113.                 httpPost.setEntity(httpEntity);  
  114.   
  115.                 logger.info(”doPost requestParams:” + EntityUtils.toString(httpEntity));  
  116.             }  
  117.             startTime = System.nanoTime();  
  118.             CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);  
  119.             int code = closeableHttpResponse.getStatusLine().getStatusCode();  
  120.   
  121.             logger.info(”doPost 状态码:” + code);  
  122.   
  123.             if (code == 200 || code == 500) {  
  124.                 try {  
  125.                     httpEntity = closeableHttpResponse.getEntity();  
  126.                     if (httpEntity != null) {  
  127.                         long length = httpEntity.getContentLength();  
  128.                         // 当返回值长度较小的时候,使用工具类读取  
  129.                         if (length != -1 && length < 2048) {  
  130.                             stringBuffer.append(EntityUtils.toString(httpEntity));  
  131.                         } else {    // 否则使用IO流来读取  
  132.                             BufferedReader bufferedReader = new BufferedReader(  
  133.                                     new InputStreamReader(httpEntity.getContent(), “UTF-8”));  
  134.                             String line;  
  135.                             while ((line = bufferedReader.readLine()) != null) {  
  136.                                 stringBuffer.append(line);  
  137.                             }  
  138.                             bufferedReader.close();  
  139.                             responseParams = stringBuffer.toString();  
  140.                         }  
  141.                         endTime = System.nanoTime();  
  142.                     }  
  143.                 } catch (Exception e) {  
  144.                     endTime = System.nanoTime();  
  145.   
  146.                     logger.info(”doPost Exception(通讯错误):” + e.getMessage());  
  147.                 } finally {  
  148.                     closeableHttpResponse.close();  
  149.                 }  
  150.             } else {  
  151.                 endTime = System.nanoTime();  
  152.                 httpPost.abort();  
  153.   
  154.                 logger.info(”doPost 错误请求,状态码:” + code);  
  155.             }  
  156.         } catch (IOException e) {  
  157.             endTime = System.nanoTime();  
  158.   
  159.             logger.info(”doPost IOException:” + e.getMessage());  
  160.         } finally {  
  161.             try {  
  162.                 closeableHttpClient.close();  
  163.             } catch (IOException e) {  
  164.             }  
  165.         }  
  166.   
  167.         logger.info(”doPost 用时(毫秒):” + (endTime - startTime) / 1000000L);  
  168.         logger.info(”doPost responseParams:” + responseParams);  
  169.   
  170.         return responseParams;  
  171.     }  
  172.   
  173.     /** 
  174.      * 向指定 URL 发送 GET请求 
  175.      * 
  176.      * @param strUrl        发送请求的 URL 
  177.      * @param requestParams 请求参数 
  178.      * @return 远程资源的响应结果 
  179.      */  
  180.     public static String sendGet(String strUrl, String requestParams) {  
  181.         logger.info(”sendGet strUrl:” + strUrl);  
  182.         logger.info(”sendGet requestParams:” + requestParams);  
  183.   
  184.         String responseParams = ”“;  
  185.         BufferedReader bufferedReader = null;  
  186.         try {  
  187.             String strRequestUrl = strUrl + ”?” + requestParams;  
  188.             URL url = new URL(strRequestUrl);  
  189.             URLConnection urlConnection = url.openConnection();    // 打开与 URL 之间的连接  
  190.   
  191.             // 设置通用的请求属性  
  192.             urlConnection.setRequestProperty(”accept”“*/*”);  
  193.             urlConnection.setRequestProperty(”connection”“Keep-Alive”);  
  194.             urlConnection.setRequestProperty(”user-agent”,  
  195.                     ”Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)”);  
  196.   
  197.             urlConnection.connect();    // 建立连接  
  198.   
  199.             Map<String, List<String>> map = urlConnection.getHeaderFields();    // 获取所有响应头字段  
  200.   
  201.             // 使用BufferedReader输入流来读取URL的响应  
  202.             bufferedReader = new BufferedReader(new InputStreamReader(  
  203.                     urlConnection.getInputStream()));  
  204.             String strLine;  
  205.             while ((strLine = bufferedReader.readLine()) != null) {  
  206.                 responseParams += strLine;  
  207.             }  
  208.         } catch (Exception e) {  
  209.             logger.info(”sendGet Exception:” + e.getMessage());  
  210.         } finally {  
  211.             try {  
  212.                 if (bufferedReader != null) {  
  213.                     bufferedReader.close();  
  214.                 }  
  215.             } catch (Exception e2) {  
  216.                 e2.printStackTrace();  
  217.             }  
  218.         }  
  219.   
  220.         logger.info(”sendPost responseParams:” + responseParams);  
  221.   
  222.         return responseParams;  
  223.     }  
  224. }  
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;
    }
}


— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

            </div>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在HTTP/1.1规范中,GET请求是不支持请求体(request body)的,只有POST请求及其它一些请求方式支持。但是在实际中,有时候需要在发送GET请求时带上一些参数,这些参数需要通过请求体来传递,这种情况下可以采用以下两种方式实现: 1. 利用HTTP Post模拟HTTP Get带body 代码示例: ```java URL url = new URL("http://example.com/resource"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("param1=value1&param2=value2"); writer.flush(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); } writer.close(); reader.close(); ``` 2. 采用HTTP Get方式,但在请求URL中带上参数 代码示例: ```java String url = "http://example.com/resource?param1=value1&param2=value2"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); ``` 需要注意的是,第二种方式虽然可以在请求体中传递参数,但是可能会被一些HTTP代理服务器或者Web服务器认为是不符合规范的请求,因此并不是所有的Web服务器都支持此方式。建议采用第一种方式来发送带请求体的请求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值