HttpURLConnection的帖子:输出流有没有影响? [英] HttpURLConnection Post: Output stream has no effect?

查看:138
本文介绍了HttpURLConnection的帖子:输出流有没有影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Android应用程序,并已发现了不同的Andr​​oid版本,对它们如何处理HTTP(S)的URLConnections不同的方式(http://stackoverflow.com/q/9556316/151682).

I am developing an Android app and have already found out that different Android versions have a different ways on how they handle Http(s)URLConnections (http://stackoverflow.com/q/9556316/151682).

我跑进的问题,安卓4.0进行通过HTTPS很好的一个POST请求,运行低于code时自动添加一个类似的Content-Type头。

I ran into the issue that Android 4 performs a POST request over HTTPS nicely, adding headers like Content-Type automatically when running the code below.

不过,在Android 2.3.5(设备及放大器;模拟器),输出流的任何写操作似乎被忽略 - 我与Web代理查尔斯调试它,而所有的头被发送,数据写入到输出流是不是一起发送...

However, on Android 2.3.5 (device & emulator), any write to the output stream seems to be ignored - I debugged it with the web proxy Charles and while all headers are sent, the data written to the output stream is not sent along...

任何人知道如何解决这个问题?

Anyone knows how to solve this?

请注意:由于我对开发API只有一个自签名的证书,我需要在这个时候禁用证书验证

Note: As the API I am developing against has only a self-signed certificate, I need to disable certification validation at this time.

TIA,帕特里克

更新
在此期间,我也有试过之后,都无济于事:

Update In the meantime, I also have tried to following, to no avail:


  • 电话的close()上的BufferedOutputStream的刷新()电话后

  • 电话的close()双方的OutputStream中和的BufferedOutputStream

  • 使用OutputStreamWriter代替

  • 不调用的close()之前调用的getInputStream()

  • Calling close() after the flush() call on the BufferedOutputStream
  • Calling close() on both the OutputStream and the BufferedOutputStream
  • Using a OutputStreamWriter instead
  • Not calling close() before calling 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();
}

}

推荐答案

嗯,我终于找到了。找错了地方...问题是头:

Ah, I finally found it. Looking in the wrong place... The problem was the headers:

我的code以上实际工作正常 - 原因是,我包含的头是连接的Base64 codeD。在我的Andr​​oid 2.3.5指定的选项( Base64.DEFAULT ),似乎在这pmaturely结束请求$ P $的末尾插入一个额外的换行,让我没时间发送实际的身体。
在Android 4,默认似乎在下面链接的帖子解释更改为类似BASE64.NO_WRAP ...

My code above actually works fine - the cause is that I included a header which is Base64 encoded. On my Android 2.3.5 the specified option (Base64.DEFAULT) seems to insert an extra newline at the end which ends the request prematurely, giving me no time to send the actual body. On Android 4, the Default seems to be changed to something like BASE64.NO_WRAP as explained in the post linked below...

这实际上已经回答这里

感谢您的努力。

这篇关于HttpURLConnection的帖子:输出流有没有影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆