• Android 开发工具类 03_HttpUtils


    Http 请求的工具类:

    1、异步的 Get 请求;

    2、异步的 Post 请求;

    3、Get 请求,获得返回数据;

    4、向指定 URL 发送 POST方法的请求。

      1 import java.io.BufferedReader;
      2 import java.io.ByteArrayOutputStream;
      3 import java.io.IOException;
      4 import java.io.InputStream;
      5 import java.io.InputStreamReader;
      6 import java.io.PrintWriter;
      7 import java.net.HttpURLConnection;
      8 import java.net.URL;
      9 
     10 // Http 请求的工具类
     11 public class HttpUtils
     12 {
     13 
     14     private static final int TIMEOUT_IN_MILLIONS = 5000;
     15 
     16     public interface CallBack
     17     {
     18         void onRequestComplete(String result);
     19     }
     20 
     21 
     22     /**
     23      * 异步的 Get 请求
     24      * 
     25      * @param urlStr
     26      * @param callBack
     27      */
     28     public static void doGetAsyn(final String urlStr, final CallBack callBack)
     29     {
     30         new Thread()
     31         {
     32             public void run()
     33             {
     34                 try
     35                 {
     36                     String result = doGet(urlStr);
     37                     if (callBack != null)
     38                     {
     39                         callBack.onRequestComplete(result);
     40                     }
     41                 } catch (Exception e)
     42                 {
     43                     e.printStackTrace();
     44                 }
     45 
     46             };
     47         }.start();
     48     }
     49 
     50     /**
     51      * 异步的 Post 请求
     52      * @param urlStr
     53      * @param params
     54      * @param callBack
     55      * @throws Exception
     56      */
     57     public static void doPostAsyn(final String urlStr, final String params,
     58             final CallBack callBack) throws Exception
     59     {
     60         new Thread()
     61         {
     62             public void run()
     63             {
     64                 try
     65                 {
     66                     String result = doPost(urlStr, params);
     67                     if (callBack != null)
     68                     {
     69                         callBack.onRequestComplete(result);
     70                     }
     71                 } catch (Exception e)
     72                 {
     73                     e.printStackTrace();
     74                 }
     75 
     76             };
     77         }.start();
     78 
     79     }
     80 
     81     /**
     82      * Get 请求,获得返回数据
     83      * 
     84      * @param urlStr
     85      * @return
     86      * @throws Exception
     87      */
     88     public static String doGet(String urlStr) 
     89     {
     90         URL url = null;
     91         HttpURLConnection conn = null;
     92         InputStream is = null;
     93         ByteArrayOutputStream baos = null;
     94         try
     95         {
     96             url = new URL(urlStr);
     97             conn = (HttpURLConnection) url.openConnection();
     98             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
     99             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
    100             conn.setRequestMethod("GET");
    101             conn.setRequestProperty("accept", "*/*");
    102             conn.setRequestProperty("connection", "Keep-Alive");
    103             if (conn.getResponseCode() == 200)
    104             {
    105                 is = conn.getInputStream();
    106                 baos = new ByteArrayOutputStream();
    107                 int len = -1;
    108                 byte[] buf = new byte[128];
    109 
    110                 while ((len = is.read(buf)) != -1)
    111                 {
    112                     baos.write(buf, 0, len);
    113                 }
    114                 baos.flush();
    115                 return baos.toString();
    116             } else
    117             {
    118                 throw new RuntimeException(" responseCode is not 200 ... ");
    119             }
    120 
    121         } catch (Exception e)
    122         {
    123             e.printStackTrace();
    124         } finally
    125         {
    126             try
    127             {
    128                 if (is != null)
    129                     is.close();
    130             } catch (IOException e)
    131             {
    132             }
    133             try
    134             {
    135                 if (baos != null)
    136                     baos.close();
    137             } catch (IOException e)
    138             {
    139             }
    140             conn.disconnect();
    141         }
    142         
    143         return null ;
    144 
    145     }
    146 
    147     /**
    148      * 向指定 URL 发送 POST 方法的请求
    149      * 
    150      * @param url
    151      *            发送请求的 URL
    152      * @param param
    153      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
    154      * @return 所代表远程资源的响应结果
    155      * @throws Exception
    156      */
    157     public static String doPost(String url, String param) 
    158     {
    159         PrintWriter out = null;
    160         BufferedReader in = null;
    161         String result = "";
    162         try
    163         {
    164             URL realUrl = new URL(url);
    165             // 打开和URL之间的连接
    166             HttpURLConnection conn = (HttpURLConnection) realUrl
    167                     .openConnection();
    168             // 设置通用的请求属性
    169             conn.setRequestProperty("accept", "*/*");
    170             conn.setRequestProperty("connection", "Keep-Alive");
    171             conn.setRequestMethod("POST");
    172             conn.setRequestProperty("Content-Type",
    173                     "application/x-www-form-urlencoded");
    174             conn.setRequestProperty("charset", "utf-8");
    175             conn.setUseCaches(false);
    176             // 发送POST请求必须设置如下两行
    177             conn.setDoOutput(true);
    178             conn.setDoInput(true);
    179             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
    180             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
    181 
    182             if (param != null && !param.trim().equals(""))
    183             {
    184                 // 获取URLConnection对象对应的输出流
    185                 out = new PrintWriter(conn.getOutputStream());
    186                 // 发送请求参数
    187                 out.print(param);
    188                 // flush输出流的缓冲
    189                 out.flush();
    190             }
    191             // 定义BufferedReader输入流来读取URL的响应
    192             in = new BufferedReader(
    193                     new InputStreamReader(conn.getInputStream()));
    194             String line;
    195             while ((line = in.readLine()) != null)
    196             {
    197                 result += line;
    198             }
    199         } catch (Exception e)
    200         {
    201             e.printStackTrace();
    202         }
    203         // 使用finally块来关闭输出流、输入流
    204         finally
    205         {
    206             try
    207             {
    208                 if (out != null)
    209                 {
    210                     out.close();
    211                 }
    212                 if (in != null)
    213                 {
    214                     in.close();
    215                 }
    216             } catch (IOException ex)
    217             {
    218                 ex.printStackTrace();
    219             }
    220         }
    221         return result;
    222     }
    223 }
  • 相关阅读:
    SQL Server和Oracle数据库索引介绍
    ITPUB上一个Oracle面试题
    国服《巫妖王之怒》3.35冰双持新手献礼指南
    WLK奥法输出循环
    flume架构初接触
    密码校验正则表达式(java 环境)
    初学Mahout测试kmeans算法
    身份证校验(java)
    gcc 中 O选项对空函数的优化
    《肖申克的救赎》语录
  • 原文地址:https://www.cnblogs.com/renzimu/p/4535633.html
Copyright © 2020-2023  润新知