Android HttpURLConnect POST流大小

时间:2016-05-20 05:48:49

标签: android http-post httpurlconnection

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

在android中进行帖子调用。我遇到的问题我不知道如何将帖子调用写入http连接。

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 个答案:

答案 0 :(得分:1)

要考虑的问题:

  1. Google图表API是否要求通过标题变量发送信息?
  2. Google图表API是否需要在正文中发送信息?
  3. 正文中的信息是否以正确的格式发送?
  4. 缺少Content-Type标头变量
  5. 为什么在标题和正文中设置了相同的数据?
  6. 阅读Google Chart Guide后,以下代码将成功向Google Chart API发出POST请求,并将图像作为字节检索。

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

    请注意以下行以设置帖子大小: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();
    }