【发布时间】:2015-01-16 09:28:28
【问题描述】:
我在 android 上使用 HttpURLConnection 时遇到一个奇怪的问题,它给了我一个状态码 501,但是当我在 curl 上尝试请求时,它给了我状态码 200。
curl -X GET \
-H "Accept-Charset: UTF-8" \
https://domain.com/v1/resource?token=token12345
这是我的HttpURLConnectionGET请求sn-p
public MyResponse get(String params) {
HttpURLConnection connection = null;
InputStreamReader inputStream = null;
BufferedReader reader = null;
MyResponse response = null;
String tokenParam = "?token=" + params;
try {
URL url = new URL(BASE_URL + API_VER + mResource + tokenParam);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(Method.GET);
connection.setRequestProperty(Header.ACCEPT_CHARSET, Value.UTF_8);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
int statusCode = connection.getResponseCode(); // code 501
inputStream = new InputStreamReader(connection.getInputStream());
reader = new BufferedReader(inputStream);
StringBuilder message = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
message.append(line);
}
response = new MyResponse();
response.setMessageBody(message.toString());
response.setStatusCode(statusCode);
if (statusCode == HTTP_OK || statusCode == HTTP_CREATED) {
response.setSuccess(true);
} else {
response.setSuccess(false);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) connection.disconnect();
try {
if (inputStream != null) inputStream.close();
if (reader != null) reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
我错过了什么吗?
【问题讨论】:
-
你应该实例化一个 HttpsUrlConnection 吗?
-
不错@harism 我会调查的
-
您已经将其实例化
connection = (HttpURLConnection) url.openConnection();501 错误在服务器端“未实现”。错过了有关 curl 的部分,抱歉,将再看一下代码。 -
如何设置使用HttpUrlConnection?如果你想要使用 org.apache 类,我有一些 HttpGet 代码
-
@ChrisHandy 我对其他方法持开放态度。如果这对你有用,我想试一试
标签: java android httpurlconnection