各種形式的JAVA網絡請求工具類POST/GET/PUT

各種形式的JAVA網絡請求工具類POST/GET/PUT

package com.utils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
public class HttpRequest {
   /**
    * 向指定 URL 發送POST方法的請求
    *
    * @param url
    *            發送請求的 URL
    * @param param
    *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
    * @return 所代表遠程資源的響應結果
    */
   public static String sendPost(String url, String param) {
      LogUtils.debug("url:" + url);
      LogUtils.debug("param:" + param);
      PrintWriter out = null;
      BufferedReader in = null;
      StringBuilder sb = new StringBuilder();
      try {
         URL realUrl = new URL(url);
         // 打開和URL之間的連接
         URLConnection conn = realUrl.openConnection();
         // 設置通用的請求屬性
         conn.setRequestProperty("accept", "*/*");
         conn.setRequestProperty("connection", "Keep-Alive");
         conn.setRequestProperty("user-agent",
               "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
         // 發送POST請求必須設置如下兩行
         conn.setDoOutput(true);
         conn.setDoInput(true);
         // 獲取URLConnection對象對應的輸出流
         out = new PrintWriter(conn.getOutputStream());
         // 發送請求參數
         out.print(param);
         // flush輸出流的緩衝
         out.flush();
         // 定義BufferedReader輸入流來讀取URL的響應
         in = new BufferedReader(
               new InputStreamReader(conn.getInputStream(), "UTF-8"));
         String line;
         while ((line = in.readLine()) != null) {
            sb.append(line);
         }
      } catch (Exception e) {
         e.printStackTrace();
         CommonMail.sendException("http post", "參數:"+param +"/n"+DealString.getFromException(e),  1);
      }
      // 使用finally塊來關閉輸出流、輸入流
      finally {
         try {
            if (out != null) {
               out.close();
            }
            if (in != null) {
               in.close();
            }
         } catch (IOException ex) {
            ex.printStackTrace();
         }
      }
      return sb.toString();
   }

   /**
    * 向指定URL發送GET方法的請求
    *
    * @param url   發送請求的URL
    * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
    * @return URL 所代表遠程資源的響應結果
    */
   public static String sendGet(String url, Map<String, String> param) {
      StringBuilder sb = new StringBuilder();
      BufferedReader in = null;
      try {
         String urlNameString = url + "?" + getParam(param);
         URL realUrl = new URL(urlNameString);
         // 打開和URL之間的連接
         URLConnection connection = realUrl.openConnection();
         // 設置通用的請求屬性
         connection.setRequestProperty("accept", "*/*");
         connection.setRequestProperty("connection", "Keep-Alive");
         connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
         connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; UTF-8");
         // 建立實際的連接
         connection.connect();
         // 獲取所有響應頭字段
         Map<String, List<String>> map = connection.getHeaderFields();
         // 遍歷所有的響應頭字段
         map.forEach((k,v)->{
            log.info("{}--->{}",k,v);
         });
         // 定義 BufferedReader輸入流來讀取URL的響應
         in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
         String line;
         while ((line = in.readLine()) != null) {
            sb.append(line);
         }
      } catch (Exception e) {
         LogUtils.debug("發送GET請求出現異常!" + e);
         e.printStackTrace();
      }
      // 使用finally塊來關閉輸入流
      finally {
         try {
            if (in != null) {
               in.close();
            }
         } catch (Exception e2) {
            e2.printStackTrace();
         }
      }
      return sb.toString();
   }

   /**
    * 向指定URL發送GET方法的請求 application/json
    *
    * @param url
    * @param json
    * @return
    */
   public static String sendPostWithJson(String url, String json) {
      String returnValue = "接口調用失敗";
      CloseableHttpClient httpClient = HttpClients.createDefault();
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      try {
         //第一步:創建HttpClient對象
         httpClient = HttpClients.createDefault();

         //第二步:創建httpPost對象
         HttpPost httpPost = new HttpPost(url);

         //第三步:給httpPost設置JSON格式的參數
         StringEntity requestEntity = new StringEntity(json, "utf-8");
         requestEntity.setContentEncoding("UTF-8");
         httpPost.setHeader("Content-type", "application/json");
         httpPost.setEntity(requestEntity);

         //第四步:發送HttpPost請求,獲取返回值
         returnValue = httpClient.execute(httpPost, responseHandler);
      } catch (Exception e) {
         e.printStackTrace();
         CommonMail.sendException("sendPostWithJson請求失敗!", "url=" + url + "\r\njson=" + json + "\r\n" + DealString.getFromException(e), 1);
      } finally {
         try {
            httpClient.close();
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
      //第五步:處理返回值
      return returnValue;
   }
   /**
    * 向指定 URL 發送POST方法的請求
    *
    * @param url
    *            發送請求的 URL
    * @param param
    *            請求參數,請求參數應該是Map的形式,請在key爲參數,value爲值。
    * @return 所代表遠程資源的響應結果
    * @throws Exception
    */
   public static String sendPost(String url, Map<String, String> param) throws Exception {
      PrintWriter out = null;
      BufferedReader in = null;
      StringBuffer result = new StringBuffer();
      try {
         URL realUrl = new URL(url);
         // 打開和URL之間的連接
         URLConnection conn = realUrl.openConnection();
         HttpURLConnection httpUrlConn = (HttpURLConnection) conn;
         // 設置通用的請求屬性
         httpUrlConn.setRequestProperty("accept", "*/*");
         httpUrlConn.setRequestProperty("connection", "Keep-Alive");
         httpUrlConn.setRequestProperty("user-agent",
               "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
         // 發送POST請求必須設置如下兩行
         httpUrlConn.setDoOutput(true);
         httpUrlConn.setDoInput(true);
         httpUrlConn.setRequestMethod("POST");
         httpUrlConn.setReadTimeout(5000);
         httpUrlConn.setConnectTimeout(5000);
         // 獲取URLConnection對象對應的輸出流
         out = new PrintWriter(httpUrlConn.getOutputStream());
         // 發送請求參數
         out.print(getParam(param));
         // flush輸出流的緩衝
         out.flush();
         // 定義BufferedReader輸入流來讀取URL的響應
         in = new BufferedReader(
               new InputStreamReader(httpUrlConn.getInputStream(),"UTF-8"));
         String line;
         while ((line = in.readLine()) != null) {
            result.append(line);
         }
      } catch (Exception e) {
         LogUtils.debug("發送 POST 請求出現異常!"+e);
         e.printStackTrace();
         throw new Exception("發送 POST 請求出現異常!",e);
      }
      //使用finally塊來關閉輸出流、輸入流
      finally{
         try{
            if(out!=null){
               out.close();
            }
            if(in!=null){
               in.close();
            }
         }
         catch(IOException ex){
            ex.printStackTrace();
         }
      }
      return result.toString();
   }

   /**
    * 向指定 URL 發送PUT方法的請求
    * @param url
    * @param json
    * @return
    */
   public static String sendPutWithJson(String url, String json) {
      String returnValue = "";
      CloseableHttpClient httpClient = HttpClients.createDefault();
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      try {
         //第一步:創建HttpClient對象
         httpClient = HttpClients.createDefault();

         //第二步:創建httpPost對象
         HttpPut httpPost = new HttpPut(url);

         //第三步:給httpPost設置JSON格式的參數
         StringEntity requestEntity = new StringEntity(json, "utf-8");
         requestEntity.setContentEncoding("UTF-8");
         httpPost.setHeader("Content-type", "application/json");
         httpPost.setEntity(requestEntity);

         //第四步:發送HttpPost請求,獲取返回值
         returnValue = httpClient.execute(httpPost, responseHandler);
      } catch (Exception e) {
         e.printStackTrace();
         CommonMail.sendException("sendPostWithJson請求失敗!", "url=" + url + "\r\njson=" + json + "\r\n" + DealString.getFromException(e), 1);
      } finally {
         try {
            httpClient.close();
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
      //第五步:處理返回值
      return returnValue;
   }
   public static String sendXiMaPost(String url, Map<String, String> paramMap) {
      String param = getParam(paramMap);
      return sendXiMaPost(url, param);
   }

   /**
    * 向指定 URL 發送POST方法的請求
    *
    * @param url   發送請求的 URL
    * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
    * @return 所代表遠程資源的響應結果
    */
   public static String sendXiMaPost(String url, String param) {
      PrintWriter out = null;
      BufferedReader in = null;
      String result = "";
      try {
         URL realUrl = new URL(url);
         // 打開和URL之間的連接
         HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
         // 設置通用的請求屬性
         conn.setRequestProperty("accept", "*/*");
         conn.setRequestProperty("connection", "Keep-Alive");
         conn.setRequestProperty("user-agent",
               "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
         // 發送POST請求必須設置如下兩行
         conn.setDoOutput(true);
         conn.setDoInput(true);
         // 獲取URLConnection對象對應的輸出流
         out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
         // 發送請求參數
         out.print(param);
         // flush輸出流的緩衝
         out.flush();
         //判斷返回碼
         if (conn.getResponseCode() == 401 || conn.getResponseCode() == 400) {
//                return "";
            in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
         } else {
            // 定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(
                  new InputStreamReader(conn.getInputStream(), "UTF-8"));
         }
         String line;
         while ((line = in.readLine()) != null) {
            result += line;
         }
      } catch (Exception e) {
         e.printStackTrace();
         CommonMail.sendException("http post", "參數:" + param + "/n" + DealString.getFromException(e), 1);
      }
      // 使用finally塊來關閉輸出流、輸入流
      finally {
         try {
            if (out != null) {
               out.close();
            }
            if (in != null) {
               in.close();
            }
         } catch (IOException ex) {
            ex.printStackTrace();
         }
      }
      return result;
   }

   /**
    * 構建請求參數
    * @param params
    * @return
    */
   public static String getParam(Map<String, String> params) {
      StringBuffer sb = new StringBuffer();
      String str = "";
      if(params!=null){
         for (Map.Entry<String, String> e : params.entrySet()) {
            sb.append(e.getKey());
            sb.append("=");
            sb.append(e.getValue());
            sb.append("&");
         }
         str = sb.substring(0, sb.length() - 1);

      }
      return str;
   }

   public static String encodeURL(String url){
      return url.replace("%", "%25").replace("+", "%2B").replace(" ", "%20").replace("/", "%2F")
            .replace("?", "%3F").replace("#", "%23").replace("&", "%26").replace("=", "%3D")
            .replace(":", "%3A");
   }

   public static String sendPostJSON(String url, String param) throws Exception {
      OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .retryOnConnectionFailure(Boolean.FALSE)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(50, TimeUnit.SECONDS)
            .build();
      RequestBody body = RequestBody.create(MediaType.parse("application/json"), param);
      Request.Builder request = new Request.Builder().post(body).url(url);
      Response response = client.newCall(request.build()).execute();
      InputStream is = response.body().byteStream();
      String s = new String(readInputStream(is));
      LogUtils.debug(s);
      return s;
   }

   private static byte[] readInputStream(InputStream inStream) throws Exception {
      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      byte[] buffer = new byte[1024];
      int len;
      while ((len = inStream.read(buffer)) != -1) {
         outStream.write(buffer, 0, len);
      }
      inStream.close();
      return outStream.toByteArray();
   }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章