• 安卓App使用HttpURLConnection发送请求与上传文件


    安卓原生App开发时常用的http开发工具

    • 系统内置http请求工具为 HttpURLConnection
    • httpClient 是 apache 的开源工具
    • okHttp 使用更简单,语法相对HttpURLConnection也简洁了许多,需要在graddle添加依赖。

    本文主要讲解如何使用HttpURConnection向服务器发送Reqest, 保存Response内容,如何上传文件等内容。

    1. 使用 HttpURLConnection 发送http GET请求

    step-1: 创建1个URL 对象

    URL url = new URL("http://www.yahoo.com");
    
    • 1

    step-2: 创建1个 HttpURLConnection对象,并绑定URL对象 object,

    HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
    
    • 1

    step-3: 设置请求方法,以及其它必要选项

    httpConn.setConnectTimeout(10000);
    httpConn.setRequestMethod("GET");
    
    • 1
    • 2

    设置了请求方法后,就开始发送

    step-4: 读取 Response
    在httpConn对象上打开1个input stream, 用BufferReader的方式从httpConnect中读字节

    InputStream inputStream = httpConn.getInputStream();
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    //保存response内容
    StringBuffer readTextBuf = new StringBuffer();
    String line = bufferedReader.readLine();
    while(line != null) {
        readTextBuf.append(line);
        // Continue to read text line.
        line = bufferedReader.readLine();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    step-5: 读完response以后,此连接就不需要了,别忘了关闭连接

    httpConn.disconnect();
    
    • 1

    2. 发送 POST请求步骤

    与GET请求步骤不同在于,POST 需要在消息体内携带请求参数,因此要在httpConn连接上打开ouput stream,才能发出
    将第1节的step-3 改为如下:

    httpConn.setRequestMethod("GET");
    httpConn.setRequestProperty(Key,Value);
    httpConn.setDoOutput(true);
    
    Output the stream to the server
    OutputStream outputPost = new BufferedOutputStream(httpConn.getOutputStream());
    writeStream(outputPost);
    outputPost.flush();
    outputPost.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    至此,POST消息发送完成。 读取Response响应体的方法与上节相同。

    下面是1个完整的发送POST 示例
    (1)准备1个HashMap(类似于python字典)保存请求参数
    HashMap params;
    //此处添加
    params.put("name", "Jack");
    params.put("company", "Baidu");
    
    • 1
    • 2
    • 3
    • 4

    (2)将HashMap转为stringBuild类型

    
     StringBuilder sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), "UTF-8"));
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    (3) 创建 HttpURLConnection 对象,打开连接,发送POST请求参数

    try{
        String url = "http://www.example.com/test.php";
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        
        conn.connect();
        
        String paramsString = sbParams.toString();  //sbParams是前面准备好的
        
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(paramsString);
        wr.flush();
        wr.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    (4)接收response, 保存body 内容

    try {
      InputStream in = new BufferedInputStream(conn.getInputStream());
      BufferedReader reader = new BufferedReader(new InputStreamReader(in));
      StringBuilder result = new StringBuilder();
      String line;
      while ((line = reader.readLine()) != null) {
        result.append(line);
      }
    
      Log.d("test", "result from server: " + result.toString());
    
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    3. 发送Json POST request

    与普通的POST请求不同,JSON POST请求参数为json格式, 因此需要修改请求头部参数Content-Type与Accept参数

    修改step-3步骤:

    httpConn.setRequestMethod("POST");
    
    • 1

    设置Content-Type头部参数为“application/json”

    httpConn.setRequestProperty("Content-Type", "application/json");
    
    • 1

    设置“Accept”头部参数为“application/json”

    httpConn.setRequestProperty("Accept", "application/json");
    
    • 1

    设置连接准备发送数据

    httpConn.setDoOutput(true);
    
    • 1

    创建1个json body

    String jsonInputString = "{"name": "Upendra", "job": "Programmer"}";
    
    • 1

    将json字符串写入output stream

    try(OutputStream os = httpConn.getOutputStream()) {
       byte[] input = jsonInputString.getBytes("utf-8");
       os.write(input, 0, input.length); 
    }
    
    • 1
    • 2
    • 3
    • 4

    4. 用POST请求上传文件

    上传文件时,POST请求头部参数Content-Type使用 multipart/form-data, 实现也比较容易

    URL url = new URL(postTarget);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
    String auth = "Bearer " + oauthToken;
    connection.setRequestProperty("Authorization", basicAuth);
    
    String boundary = UUID.randomUUID().toString();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
    
    DataOutputStream request = new DataOutputStream(uc.getOutputStream());
    
    request.writeBytes("--" + boundary + "\r\n");
    request.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");
    request.writeBytes(fileDescription + "\r\n");
    
    request.writeBytes("--" + boundary + "\r\n");
    request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.fileName + "\"\r\n\r\n");
    request.write(FileUtils.readFileToByteArray(file));
    request.writeBytes("\r\n");
    
    request.writeBytes("--" + boundary + "--\r\n");
    request.flush();
    int respCode = connection.getResponseCode();
    
    switch(respCode) {
        case 200:
            //all went ok - read response
            ...
            break;
        case 301:
        case 302:
        case 307:
            //handle redirect - for example, re-post to the new location
            ...
            break;
        ...
        default:
            //do something sensible
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    总结

    使用 HttpURLConnection 发送请求流程还是比较清晰,GET, POST,主要的区别在Step-3 步骤,发送 JSON类型参数,上传 file 还需要修改头部参数。
    在Android App开发时,可以在Activity用按钮事件来触发请求,也可以使用service 在后台发送请求。 本文就不列出那些示例代码了。

  • 相关阅读:
    【MySQL篇】数据库角色
    抽象类和接口
    Redis面试题:redis做为缓存,数据的持久化是怎么做的?两种持久化方式有什么区别呢?这两种方式,哪种恢复的比较快呢?
    A+轮融资近2亿元,本土线控制动「TOP 1」按下“加速键”
    金融业需要的大模型,是一个系统化工程
    springboot+高校教室排课系统 毕业设计-附源码221556
    你不知道的 console.log 替代品
    这样在 C# 使用 LongRunnigTask 是错的
    C++的缺陷和思考(四)
    JavaEE——Java线程的几种状态
  • 原文地址:https://blog.csdn.net/captain5339/article/details/133698350