我正在开发一个 Android 应用程序,并且已经发现不同的 Android 版本在处理 Http(s)URLConnections 方面有不同的方式 (http://stackoverflow.com/q/9556316/151682)。
我遇到了这样的问题:Android 4 很好地通过 HTTPS 执行 POST 请求,在运行下面的代码时自动添加 Content-Type 等标头。
然而,在 Android 2.3.5(设备和模拟器)上,对输出流的任何写入似乎都会被忽略 - 我使用 Web 代理 Charles 对其进行了调试,并且在发送所有标头时,写入输出流的数据不会一起发送...
有人知道如何解决这个问题吗?
注意:由于我正在开发的 API 只有自签名证书,因此我此时需要禁用证书验证。
蒂亚,帕特里克
Update同时,我也尝试过以下操作,但无济于事:
- Calling
close()
之后flush()
调用 BufferedOutputStream
- Calling
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();
}
}
对我来说,你打电话的顺序似乎是DoSetOutput
等等是奇怪行为的原因......
一些带有 Android 上 HTTP POST 工作代码的链接/源代码:
-
Android 上的 HttpURLConnection 失败(参见问题中的班级作为参考)
-
HttpURL连接(参考包括示例代码)
- 很好的示例,包括异常处理
- http://digitallibraryworld.com/?p=189
- 如何使用 DefaultHttpClient 写入 OutputStream?
-
DefaultHttpClient GET 和 POST 命令 Java Android(参见相关代码)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)