Cor*_*ius 9 java android http android-4.0-ice-cream-sandwich
自更新到冰淇淋三明治后,我的POST请求不再起作用.在ICS之前,这很好用:
try {
final URL url = new URL("http://example.com/api/user");
final HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(false);
connection.setDoInput(true);
connection.setRequestProperty("Content-Length", "0");
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.w(RestUploader.class.getSimpleName(), ": response code: " + connection.getResponseMessage());
} else {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
final String line = reader.readLine();
reader.close();
return Long.parseLong(line);
}
} catch (final MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
Run Code Online (Sandbox Code Playgroud)
我试着设定
connection.setDoOutput(true);
Run Code Online (Sandbox Code Playgroud)
但它不起作用.服务器响应始终为405(方法不允许),服务器日志表明它是GET请求.
Android JavaDoc to setRequestMethod说:
只能在建立连接之前调用此方法.
这是否意味着必须在url.openConnection()之前调用该方法?我应该如何创建HttpURLConnection实例?我见过的所有例子,如上所述.
我希望有人知道为什么它总是发送一个GET请求而不是POST.
提前致谢.
小智 0
connection.setRequestMethod("POST");
connection.setDoOutput(false);
Run Code Online (Sandbox Code Playgroud)
在上面两个语句中只需放置
connection.setDoOutput(true)
Run Code Online (Sandbox Code Playgroud)
前
connection.setRequestMethod("POST")
Run Code Online (Sandbox Code Playgroud)
陈述