URL url = new URL("http://myserver.com/myendpoint");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//connection.setRequestMethod("POST") <- this didn't help either
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("string=test");
out.close();
connection.close()
桌面JVM上的WORKS上面的代码,发送一个post请求,在服务器端成功解析了响应200,但是在android上,请求方法保持GET(是的,我检查它是假的)并导致404异常。官方文档说将doOutput设置为true触发器将请求方法设置为POST但似乎并非如此。
答案 0 :(得分:4)
404也不例外。它是您发出请求的服务器返回的HTTP状态代码,这意味着找不到您发出请求的URL。这与POST设置无关。
要检查的事项:
额外信息:如果网址已在服务上注册,但不允许POST请求,则会收到415响应代码。
答案 1 :(得分:1)
将数据发布到服务器时,我正在设置一些额外的请求标头:
String query = "string=test";
URL url = new URL("http://myserver.com/myendpoint");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
connection.setFixedLengthStreamingMode(query.getBytes("UTF-8").length);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(query);
但正如所建议的那样,404异常通常意味着您尝试访问的端点不可用。
答案 2 :(得分:0)
试一试:
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");