Android HttpURLConnect POST 流大小

Android HttpURLConnect POST Stream Size

我正在尝试按照此处的教程进行操作 https://developer.android.com/reference/java/net/HttpURLConnection.html

在 android 进行 post 通话。我遇到的问题我不确定如何编写对 http 连接的 post 调用。

URL url = new URL("https://chart.googleapis.com/chart");
            HttpURLConnection client = null;
            client = (HttpURLConnection) url.openConnection();
            client.setRequestMethod("POST");

            client.setRequestProperty("cht", "lc");
            client.setRequestProperty("chtt", "This is | my chart");
            client.setRequestProperty("chs", "300x200");
            client.setRequestProperty("chxt", "x");
            client.setRequestProperty("chd", "t:40,20,50,20,100");
            client.setDoOutput(true);
            client.setChunkedStreamingMode(0);

            OutputStream outputPost = new BufferedOutputStream(client.getOutputStream());
            outputPost.write(client.getRequestProperties().toString().getBytes());
            outputPost.flush();
            outputPost.close();

            InputStream in = new BufferedInputStream(client.getInputStream());
            Log.d(TAG, "Input" + in.read());
            client.disconnect();
        } catch (MalformedURLException error) {
            //Handles an incorrectly entered URL
            Log.d(TAG, "MalformedURL");
        } catch (SocketTimeoutException error) {
//Handles URL access timeout.
            Log.d(TAG, "Socket Timeout");
        } catch (IOException error) {
//Handles input and output errors
            Log.d(TAG, "IOexception");
        }

本教程使用自定义方法写入流,但我仍然 运行 为 POST 的正文写入未知数量的字节。

要考虑的问题:

  1. Google 图表 API 是否需要通过 header 变量发送信息?
  2. Google 图表 API 是否需要在 body 中发送信息?
  3. body 中的信息是否以正确的格式发送?
  4. 缺少 Content-Type header 变量
  5. 为什么 header 和 body 中设置的数据相同?

读取 Google Chart Guide 后,以下代码将成功向 Google 图表 API 发出 POST 请求并以字节形式检索图像。

要写入 post 数据,请参阅 getImage 代码示例中的以下行:con.getOutputStream().write(postDataBytes);

注意以下行以设置 post 大小:con.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));

  public byte[] getImage() throws IOException {
    URL obj = new URL("https://chart.googleapis.com/chart");
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // Store the post data
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("cht", "lc");
    params.put("chtt", "This is | my chart");
    params.put("chs", "300x200");
    params.put("chxt", "x");
    params.put("chd", "t:40,20,50,20,100");

    // Build the post data into appropriate format
    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }

    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    con.setDoOutput(true);

    // post the data
    con.getOutputStream().write(postDataBytes);

    // opens input stream from the HTTP connection
    InputStream inputStream = con.getInputStream();

    // read the data from response
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
    int n;

    while ( (n = inputStream.read(byteChunk)) > 0 ) {
        baos.write(byteChunk, 0, n);
    }

    inputStream.close();
    return baos.toByteArray();
}