HttpURLConnection Post:输出流没有效果?

Pat*_*ick 3 post android httpurlconnection

我正在开发一个Android应用程序,并且已经发现不同的Android版本在处理Http(s)URLConnections(http://stackoverflow.com/q/9556316/151682)方面有不同的方法.

我遇到了Android 4很好地通过HTTPS执行POST请求的问题,在运行下面的代码时会自动添加Content-Type等标题.

但是,在Android 2.3.5(设备和模拟器)上,对输出流的任何写入似乎都被忽略 - 我使用Web代理Charles调试它,并且在发送所有标头时,写入输出流的数据不会被发送...

谁知道如何解决这个问题?

注意:由于我正在开发的API只有一个自签名证书,我需要在此时禁用证书验证.

蒂娜,帕特里克

更新 在此期间,我也试图跟随,但无济于事:

  • 在BufferedOutputStream上调用close()之后flush()调用
  • 调用close()OutputStream和BufferedOutputStream
  • 改为使用OutputStreamWriter
  • 在打电话close()前没有打电话getInputStream()

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(CONNECT_TIMEOUT);
    
    connection.setDoOutput(true); // Triggers POST.
    connection.setRequestMethod("POST");
    int contentLength = 0;
    if(body != null) {
        contentLength = body.getBytes().length;
    }
    
    // Workarounds for older Android versions who do not do that automatically (2.3.5 for example)
    connection.setRequestProperty(HTTP.TARGET_HOST, url.getHost());
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    
    // Set SSL Context -- Development only
    if(context != null && connection instanceof HttpsURLConnection){
        HttpsURLConnection conn = (HttpsURLConnection)connection;
        conn.setSSLSocketFactory(context.getSocketFactory());
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }
    
    try{
        // Add headers
        if(headers != null){
            for (NameValuePair nvp : headers) {
                if(nvp != null){
                    connection.setRequestProperty(nvp.getName(), nvp.getValue());
                }
            }
        }
    
        connection.setFixedLengthStreamingMode(contentLength);
        OutputStream outputStream = null;
        try {
            if(body != null){
                outputStream = connection.getOutputStream();
                BufferedOutputStream stream = new BufferedOutputStream(outputStream);
                stream.write(body.getBytes()); // <<<< No effect ?!
                stream.flush();
    
            }
        } finally {
            if (outputStream != null) 
                try { 
                    outputStream.close(); 
                }
            catch (IOException logOrIgnore) {
                // ...
            }
        }
    
        InputStream inputStream = connection.getInputStream();
    
        // .... Normal case ....
    
    }
    catch(IOException e){
        // ... Exception! Check Error stream and the response code ...
    
    
    }
    finally{
        connection.disconnect();
    }
    
    Run Code Online (Sandbox Code Playgroud)

    }

Yah*_*hia 6

对我来说,你打电话DoSetOutput等的顺序似乎是奇怪行为的原因......

一些链接/来源与Android上HTTP POST的工作代码: