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

时间:2025-03-28 08:12:15
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import .;  
  •   
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  •   
  • public class HttpRequestUtils {  
  •   
  •     private static Logger logger = (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) {  
  •         (”sendPost strUrl:” + strUrl);  
  •         (”sendPost requestParams:” + requestParams);  
  •   
  •         URL url = null;  
  •         HttpURLConnection httpURLConnection = null;  
  •         try {  
  •             url = new URL(strUrl);  
  •             httpURLConnection = (HttpURLConnection) ();  
  •             (true);  
  •             (true);  
  •             (”POST”);  
  •             (false);  
  •             (”Accept”“application/json”);    // 设置接收数据的格式  
  •             (”Content-Type”“application/json”);  // 设置发送数据的格式  
  •             ();    // 建立连接  
  •             OutputStreamWriter outputStreamWriter = new OutputStreamWriter(  
  •                     (), ”UTF-8”);  
  •             (requestParams);  
  •             ();  
  •             ();  
  •   
  •             // 使用BufferedReader输入流来读取URL的响应  
  •             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(  
  •                     (), ”utf-8”));  
  •             StringBuffer stringBuffer = new StringBuffer();  
  •             String strLine = ”“;  
  •             while ((strLine = ()) != null) {  
  •                 (strLine);  
  •             }  
  •             ();  
  •             String responseParams = ();  
  •   
  •             (”sendPost responseParams:” + responseParams);  
  •   
  •             return responseParams;  
  •         } catch (IOException e) {  
  •             (”sendPost IOException:” + ());  
  •         } finally {  
  •             if (httpURLConnection != null) {  
  •                 ();  
  •             }  
  •         }  
  •   
  •         return null;  
  •     }  
  •   
  •     /** 
  •      * HttpClientPost 方式,向指定 URL 发送 POST请求 
  •      * 
  •      * @param strUrl        发送请求的 URL 
  •      * @param requestParams 请求参数 
  •      * @return 远程资源的响应结果 
  •      */  
  •     public static String doPost(String strUrl, List<BasicNameValuePair> requestParams) {  
  •         (”doPost strUrl:” + strUrl);  
  •         (”doPost requestParams:” + requestParams);  
  •   
  •         String responseParams = ”“;  
  •         StringBuffer stringBuffer = new StringBuffer();  
  •         long startTime = 0, endTime = 0;  
  •   
  •         CloseableHttpClient closeableHttpClient = ();  
  •   
  •         RequestConfig requestConfig = ()  
  •                 .setConnectTimeout(connectTimeout)  
  •                 .setSocketTimeout(socketTimeout)  
  •                 .build();    // 设置请求和传输超时时间  
  •   
  •         HttpPost httpPost = new HttpPost(strUrl);  
  •         (requestConfig);  
  •         HttpEntity httpEntity;  
  •   
  •         try {  
  •             if (requestParams != null) {  
  •                 // 设置相关参数  
  •                 httpEntity = new UrlEncodedFormEntity(requestParams, “UTF-8”);  
  •                 (httpEntity);  
  •   
  •                 (”doPost requestParams:” + (httpEntity));  
  •             }  
  •             startTime = ();  
  •             CloseableHttpResponse closeableHttpResponse = (httpPost);  
  •             int code = ().getStatusCode();  
  •   
  •             (”doPost 状态码:” + code);  
  •   
  •             if (code == 200 || code == 500) {  
  •                 try {  
  •                     httpEntity = ();  
  •                     if (httpEntity != null) {  
  •                         long length = ();  
  •                         // 当返回值长度较小的时候,使用工具类读取  
  •                         if (length != -1 && length < 2048) {  
  •                             ((httpEntity));  
  •                         } else {    // 否则使用IO流来读取  
  •                             BufferedReader bufferedReader = new BufferedReader(  
  •                                     new InputStreamReader((), “UTF-8”));  
  •                             String line;  
  •                             while ((line = ()) != null) {  
  •                                 (line);  
  •                             }  
  •                             ();  
  •                             responseParams = ();  
  •                         }  
  •                         endTime = ();  
  •                     }  
  •                 } catch (Exception e) {  
  •                     endTime = ();  
  •   
  •                     (”doPost Exception(通讯错误):” + ());  
  •                 } finally {  
  •                     ();  
  •                 }  
  •             } else {  
  •                 endTime = ();  
  •                 ();  
  •   
  •                 (”doPost 错误请求,状态码:” + code);  
  •             }  
  •         } catch (IOException e) {  
  •             endTime = ();  
  •   
  •             (”doPost IOException:” + ());  
  •         } finally {  
  •             try {  
  •                 ();  
  •             } catch (IOException e) {  
  •             }  
  •         }  
  •   
  •         (”doPost 用时(毫秒):” + (endTime - startTime) / 1000000L);  
  •         (”doPost responseParams:” + responseParams);  
  •   
  •         return responseParams;  
  •     }  
  •   
  •     /** 
  •      * 向指定 URL 发送 GET请求 
  •      * 
  •      * @param strUrl        发送请求的 URL 
  •      * @param requestParams 请求参数 
  •      * @return 远程资源的响应结果 
  •      */  
  •     public static String sendGet(String strUrl, String requestParams) {  
  •         (”sendGet strUrl:” + strUrl);  
  •         (”sendGet requestParams:” + requestParams);  
  •   
  •         String responseParams = ”“;  
  •         BufferedReader bufferedReader = null;  
  •         try {  
  •             String strRequestUrl = strUrl + ”?” + requestParams;  
  •             URL url = new URL(strRequestUrl);  
  •             URLConnection urlConnection = ();    // 打开与 URL 之间的连接  
  •   
  •             // 设置通用的请求属性  
  •             (”accept”“*/*”);  
  •             (”connection”“Keep-Alive”);  
  •             (”user-agent”,  
  •                     ”Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)”);  
  •   
  •             ();    // 建立连接  
  •   
  •             Map<String, List<String>> map = ();    // 获取所有响应头字段  
  •   
  •             // 使用BufferedReader输入流来读取URL的响应  
  •             bufferedReader = new BufferedReader(new InputStreamReader(  
  •                     ()));  
  •             String strLine;  
  •             while ((strLine = ()) != null) {  
  •                 responseParams += strLine;  
  •             }  
  •         } catch (Exception e) {  
  •             (”sendGet Exception:” + ());  
  •         } finally {  
  •             try {  
  •                 if (bufferedReader != null) {  
  •                     ();  
  •                 }  
  •             } catch (Exception e2) {  
  •                 ();  
  •             }  
  •         }  
  •   
  •         (”sendPost responseParams:” + responseParams);  
  •   
  •         return responseParams;  
  •     }  
  • }