Java Android JSON通过HttpURLConnection获取错误405
因此,我正在尝试对我的web服务执行GET请求,因为我看到HttpGet类被弃用,所以我尝试使用HttpURLConnection类,并通过一个“POST”方法成功地使用了它。。。然而,当我尝试执行一个简单的“GET”请求时,我得到了一个405错误(坏方法) 我测试了DHC的链接,链接很好 以下是我的方法:Java Android JSON通过HttpURLConnection获取错误405,java,android,json,httpurlconnection,Java,Android,Json,Httpurlconnection,因此,我正在尝试对我的web服务执行GET请求,因为我看到HttpGet类被弃用,所以我尝试使用HttpURLConnection类,并通过一个“POST”方法成功地使用了它。。。然而,当我尝试执行一个简单的“GET”请求时,我得到了一个405错误(坏方法) 我测试了DHC的链接,链接很好 以下是我的方法: public JSONObject getClientByDeviceId (String link) { try { URL url = new URL(l
public JSONObject getClientByDeviceId (String link) {
try {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod("GET");
// conn.setDoOutput(true);
// conn.setDoInput(true);
// conn.setUseCaches(false);
// conn.setAllowUserInteraction(false);
// conn.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream = conn.getOutputStream();
outputStream.close();
if (conn.getResponseCode() != 200) {
Log.e("conn", "Error code: " + conn.getResponseCode());
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
conn.disconnect();
JSONObject returnedObject = new JSONObject(sb.toString());
if (returnedObject != null) {
Log.e("conn", "If 400, this is the object gained: " + returnedObject.getString("Message"));
} else {
Log.e("conn", "didn't get any JSON object");
}
conn.disconnect();
return returnedObject;
}
else {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
Log.e("conn", "GREAT SUCCESS !!: " + conn.getResponseCode());
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
conn.disconnect();
JSONObject returnedObject = new JSONObject(sb.toString());
return returnedObject;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
通常我会说,这个问题是由试图在“POST”URL中执行“GET”请求引起的。但是如果没有这两个HttpGet和HttpPost类,我真的不知道该向何处求助,所有被注释掉的属性都是这样的,因为我在POST请求中尝试了它们,现在我一个接一个地删除了它们,以使该方法正常工作
有什么想法吗?或者参考关于如何正确使用该HttpURLConnection类的更新指南,因为我找不到
提前谢谢 HTTP 405是由错误的方法调用(不允许方法)引起的。这意味着您在POST请求时调用了GET方法,反之亦然。您应该在Web服务上添加处理GET方法以使其工作。解决了它,显然需要删除以下代码:
OutputStream outputStream = conn.getOutputStream();
outputStream.close();
我猜这是因为我给出了一个GET URL,并将输出流放在我的代码中,这导致了问题
然而,我仍然不明白为什么我得到了“405:methodget not allowed”,而我认为我应该得到相反的结果:“POST”not allowed
不管怎样,这就是我的解决方案,非常感谢你们的帮助 对于仍然通过搜索引擎到达这里的人,我的解决方案与之类似-
我删除了行“conn.setDoOutput(true);”(或将其设置为false)您在Postman上试用过吗?是的,在DHC(另一个Chrome扩展)上也试用过-他们没有返回405错误,然后询问正在使用此web服务的php开发人员。即使当我使用“old”HttpGet时,我也得到了肯定的结果?