HttpUtils 用於進行網路請求的工具類

來源:互聯網
上載者:User

標籤:str   exce   nts   cache   get請求   print   throw   style   line   

原文:http://www.open-open.com/code/view/1437537162631

 

import java.io.BufferedReader;      import java.io.ByteArrayOutputStream;      import java.io.IOException;      import java.io.InputStream;      import java.io.InputStreamReader;      import java.io.PrintWriter;      import java.net.HttpURLConnection;      import java.net.URL;            //Http請求的工具類      public class HttpUtils      {                private static final int TIMEOUT_IN_MILLIONS = 5000;                public interface CallBack          {              void onRequestComplete(String result);          }                      /**          * 非同步Get請求          *           * @param urlStr          * @param callBack          */          public static void doGetAsyn(final String urlStr, final CallBack callBack)          {              new Thread()              {                  public void run()                  {                      try                      {                          String result = doGet(urlStr);                          if (callBack != null)                          {                              callBack.onRequestComplete(result);                          }                      } catch (Exception e)                      {                          e.printStackTrace();                      }                        };              }.start();          }                /**          * 非同步Post請求          * @param urlStr          * @param params          * @param callBack          * @throws Exception          */          public static void doPostAsyn(final String urlStr, final String params,                  final CallBack callBack) throws Exception          {              new Thread()              {                  public void run()                  {                      try                      {                          String result = doPost(urlStr, params);                          if (callBack != null)                          {                              callBack.onRequestComplete(result);                          }                      } catch (Exception e)                      {                          e.printStackTrace();                      }                        };              }.start();                }                /**          * Get請求,獲得返回資料          *           * @param urlStr          * @return          * @throws Exception          */          public static String doGet(String urlStr)           {              URL url = null;              HttpURLConnection conn = null;              InputStream is = null;              ByteArrayOutputStream baos = null;              try              {                  url = new URL(urlStr);                  conn = (HttpURLConnection) url.openConnection();                  conn.setReadTimeout(TIMEOUT_IN_MILLIONS);                  conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);                  conn.setRequestMethod("GET");                  conn.setRequestProperty("accept", "*/*");                  conn.setRequestProperty("connection", "Keep-Alive");                  if (conn.getResponseCode() == 200)                  {                      is = conn.getInputStream();                      baos = new ByteArrayOutputStream();                      int len = -1;                      byte[] buf = new byte[128];                            while ((len = is.read(buf)) != -1)                      {                          baos.write(buf, 0, len);                      }                      baos.flush();                      return baos.toString();                  } else                  {                      throw new RuntimeException(" responseCode is not 200 ... ");                  }                    } catch (Exception e)              {                  e.printStackTrace();              } finally              {                  try                  {                      if (is != null)                          is.close();                  } catch (IOException e)                  {                  }                  try                  {                      if (baos != null)                          baos.close();                  } catch (IOException e)                  {                  }                  conn.disconnect();              }                            return null ;                }                /**           * 向指定 URL 發送POST方法的請求           *            * @param url           *            發送請求的 URL           * @param param           *            請求參數,請求參數應該是 name1=value1&name2=value2 的形式。           * @return 所代表遠端資源的響應結果           * @throws Exception           */          public static String doPost(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.setRequestMethod("POST");                  conn.setRequestProperty("Content-Type",                          "application/x-www-form-urlencoded");                  conn.setRequestProperty("charset", "utf-8");                  conn.setUseCaches(false);                  // 發送POST請求必須設定如下兩行                  conn.setDoOutput(true);                  conn.setDoInput(true);                  conn.setReadTimeout(TIMEOUT_IN_MILLIONS);                  conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);                        if (param != null && !param.trim().equals(""))                  {                      // 擷取URLConnection對象對應的輸出資料流                      out = new PrintWriter(conn.getOutputStream());                      // 發送請求參數                      out.print(param);                      // flush輸出資料流的緩衝                      out.flush();                  }                  // 定義BufferedReader輸入資料流來讀取URL的響應                  in = new BufferedReader(                          new InputStreamReader(conn.getInputStream()));                  String line;                  while ((line = in.readLine()) != null)                  {                      result += line;                  }              } catch (Exception e)              {                  e.printStackTrace();              }              // 使用finally塊來關閉輸出資料流、輸入資料流              finally              {                  try                  {                      if (out != null)                      {                          out.close();                      }                      if (in != null)                      {                          in.close();                      }                  } catch (IOException ex)                  {                      ex.printStackTrace();                  }              }              return result;          }      }  

 

HttpUtils 用於進行網路請求的工具類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.