Android封装HttpURLConnection类的自定义HTTP请求方法

  在Android开发过程中,我们经常会遇到调用后台服务的情况。目前我手上进行的项目,后台服务基本上基于.NET环境开发的,开发语言是C#。服务一般是供前端AJAX请求调用。

  而在Android中,我们也可以通过HTTP请求访问类似的服务,主要请求方法都是GET或者POST,并且POST请求包含了冗长的参数。因此我自己封装了GET和POST的HTTP请求的方法,POST请求参数通过输入流写入,方法使用的是HttpURLConnection类。

  话不多说,我直接贴上方法的代码:

  1      /**
  2    * Post服务请求
  3      *
  4      * @param requestUrl 请求地址
  5      * @param requestbody 请求参数
  6      * @return
  7      */
  8     public static String sendPost(String requestUrl, String requestbody){
  9 
 10         try {
 11             //建立连接
 12             URL url = new URL(requestUrl);
 13             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 14 
 15             //设置连接属性
 16             connection.setDoOutput(true); //使用URL连接进行输出
 17             connection.setDoInput(true); //使用URL连接进行输入
 18             connection.setUseCaches(false); //忽略缓存
 19             connection.setRequestMethod("POST"); //设置URL请求方法
 20             String requestString = requestbody;
 21 
 22             //设置请求属性
 23             byte[] requestStringBytes = requestString.getBytes(); //获取数据字节数据
 24             connection.setRequestProperty("Content-length", "" + requestStringBytes.length);
 25             connection.setRequestProperty("Content-Type", "application/octet-stream");
 26             connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
 27             connection.setRequestProperty("Charset", "UTF-8");
 28 
 29             connection.setConnectTimeout(8000);
 30             connection.setReadTimeout(8000);
 31 
 32             //建立输出流,并写入数据
 33             OutputStream outputStream = connection.getOutputStream();
 34             outputStream.write(requestStringBytes);
 35             outputStream.close();
 36 
 37             //获取响应状态
 38             int responseCode = connection.getResponseCode();
 39 
 40             if (HttpURLConnection.HTTP_OK == responseCode) { //连接成功
 41                 //当正确响应时处理数据
 42                 StringBuffer buffer = new StringBuffer();
 43                 String readLine;
 44                 BufferedReader responseReader;
 45                 //处理响应流
 46                 responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
 47                 while ((readLine = responseReader.readLine()) != null) {
 48                     buffer.append(readLine).append("\n");
 49                 }
 50                 responseReader.close();
 51                 Log.d("HttpPOST", buffer.toString());
 52                 return buffer.toString();//成功
 53             }
 54         }catch (Exception e){
 55             e.printStackTrace();
 56         }
 57         return 2;//失败
 58 
 59     }
 60 
 61     /**
 62      * Get服务请求
 63      *
 64      * @param requestUrl
 65      * @return
 66      */
 67     public static String sendGet(String requestUrl){
 68         try{
 69             //建立连接
 70             URL url = new URL(requestUrl);
 71             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 72 
 73             connection.setRequestMethod("GET");
 74             connection.setDoOutput(false);
 75             connection.setDoInput(true);
 76 
 77             connection.setConnectTimeout(8000);
 78             connection.setReadTimeout(8000);
 79 
 80             connection.connect();
 81 
 82             //获取响应状态
 83             int responseCode = connection.getResponseCode();
 84 
 85             if (HttpURLConnection.HTTP_OK == responseCode) { //连接成功
 86                 //当正确响应时处理数据
 87                 StringBuffer buffer = new StringBuffer();
 88                 String readLine;
 89                 BufferedReader responseReader;
 90                 //处理响应流
 91                 responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
 92                 while ((readLine = responseReader.readLine()) != null) {
 93                     buffer.append(readLine).append("\n");
 94                 }
 95                 responseReader.close();
 96                 Log.d("HttpGET", buffer.toString());
 97                 //JSONObject result = new JSONObject(buffer.toString());
 98                 return buffer.toString();
 99             }
100         }catch (Exception e){
101             e.printStackTrace();
102         }
103         return null;
104     }

  当处理响应流时,返回的可能为不同格式的字符串,这里方法返回的是String类型的字符串,可以得到String类型的返回值后再将其转换为JSONObject或JSONArray格式。

  需要注意的是,HTTP请求的方法是不允许在主UI线程中进行的,一定要进行多线程操作。下面是一段简单的实例:

new Thread(new Runnable() {
    @Override
    public void run() {
        String result = HttpUtils.sendPost(BaseHttp.METHOD.ADDLAMP,data);
    }
}).start();    

  欢迎大家批评指教!

posted @ 2017-06-21 17:58  Klose_Jiao  阅读(4385)  评论(0编辑  收藏  举报