【问题标题】:Android HttpURLConnect POST Stream SizeAndroid HttpURLConnection POST 流大小
【发布时间】:2016-05-20 05:48:48
【问题描述】:

我正在尝试按照这里的教程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 正文写入未知数量的字节。

【问题讨论】:

    标签: android http-post httpurlconnection


    【解决方案1】:

    需要考虑的问题:

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

    读取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();
    }
    

    【讨论】:

    • 感谢发布后,我开始考虑将消息正文与客户端分开。你知道如果你使用 .setRequestProperty 是否将信息放在标题上,因此在建立连接时发送而不使用写入流?
    • 信息在不写入流的情况下发送,但取决于 google api 是否会在请求标头中查找信息...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多