以下代码在我的PC上运行正常,服务器返回200 Ok
以及正确的输出。当我在Android上试用它时,服务器会重新运行:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Error 405 Method Not Allowed</title>
</head>
<body><h2>HTTP ERROR 405</h2>
<p>Problem accessing /sg-1/locations/. Reason:
<pre> Method Not Allowed</pre></p><hr><i><small>Powered by Jetty://</small></i><hr/></html>
代码:
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
// connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Session", token);
connection.connect();
InputStream response;
boolean worked = false;
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
response = connection.getErrorStream();
else {
response = connection.getInputStream();
worked = true;
}
java.util.Scanner s = new java.util.Scanner(response).useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";
System.out.println(result);
答案 0 :(得分:0)
您的代码在Java SE中发送GET
,在Android中发送POST
。似乎服务器期待GET
请求,因此请阻止在Android中发送POST
:
// connection.setDoOutput(true);