java - Android 上的 HttpURLConnection GET 请求给出奇怪的 501 代码

标签 java android httpurlconnection

在 Android 上使用 HttpURLConnection 时,我遇到了一个奇怪的问题,它给了我一个状态代码 501,但是当我在curl 上尝试请求时,它给了我状态代码 200。

curl -X GET \
-H "Accept-Charset: UTF-8" \
https://domain.com/v1/resource?token=token12345

这是我的 HttpURLConnection GET 请求 fragment

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;
}

我错过了什么吗?

最佳答案

setDoOutput(true) 用于 POST 和 PUT 请求,用于发送(输出)请求正文。通常我们不需要这个来处理 GET 请求。找到了here

关于java - Android 上的 HttpURLConnection GET 请求给出奇怪的 501 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27980798/

相关文章:

java - 从 swingworker 或在 swingworker 之后更新 JList

java - Vertx 和 Spring Boot 的区别

android - 在插入耳机的情况下通过扬声器播放音频

android - 我在哪里可以查看 Google Analytics 上跟踪器发送的数据?

java - DataOutputStream 和 OutputStreamWriter 的区别 : String compatibility?

java - 获取在线 Web 服务应用程序的应用程序模块的最佳实践

java - 自定义 log4j 适配器

android - ADB 未响应 - 等待更多或终止 adb 或重新启动 (Ubuntu 13) 64 位

java - HttpURLConnection 中的内容长度

Java Android 滚动到底部并获取新数据后总是转到第一个数据/页面(顶部回收 View )