【发布时间】:2015-03-23 09:31:45
【问题描述】:
所以我正在尝试对我的 Web 服务进行 GET 请求,因为我看到 HttpGet 类已被弃用,所以我尝试改用 HttpURLConnection 类,并通过“POST”方法成功使用它...但是,当我尝试执行简单的“GET”请求时 - 我收到 405 错误(错误方法)。
我在DHC中测试了链接,链接没问题。
这是我的方法:
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 类的更新指南,因为我找不到。
提前致谢!
【问题讨论】:
-
你在 Postman 上试过了吗?
-
是的,而且在 DHC(另一个 Chrome 扩展程序)中 - 他们没有返回 405 错误
-
然后询问您的 php 开发人员,谁正在开发此 Web 服务。
-
即使当我使用“旧”HttpGet 时,我也会得到积极的结果?
标签: java android json httpurlconnection