【问题标题】:Make a HTTP/1.1 GET request in android在 android 中发出 HTTP/1.1 GET 请求
【发布时间】:2017-09-27 21:20:14
【问题描述】:

我正在尝试从 API 请求数据。API 的要求如下:

我们 API 的基本 URL 是 https://api.openload.co/1(注意 1 /) 后面的版本 1

对 API 的所有请求都应为 HTTP/1.1 GET

请确保仅将 API 与 https 一起使用。

大多数请求都需要 API 登录和 API 密钥,您可以在 “用户设置”选项卡中的用户面板。响应是json,结构是 如下:

{    "status": <status-code>,

    "msg": "<informational message. might vary, use the status code in your code!>",

    "result": <result of the request. varies depending on the request>
}

我正在使用以下方法来获取 json 响应:

private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpsURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {

        urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect()

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            // Closing the input stream could throw an IOException, which is why
            // the makeHttpRequest(URL url) method signature specifies than an IOException
            // could be thrown.
            inputStream.close();
        }
    }
    return jsonResponse;
}

但我收到了响应代码 403。 我正在使用下面的 url 来测试它: https://api.openload.co/1/account/info?login={login}&key={key}

当从 chrome 请求时,响应是以文件的形式获得的。这是否会导致问题,因为我期待一个 json 响应字符串并且服务器正在返回一个包含 json 的文件?

有人能指出我做错了什么,就好像我在 chrome 中使用相同的 url 我得到了 json 响应,但似乎无法通过代码得到响应。

【问题讨论】:

  • 试试 urlConnection.getResponseCode() == "200"
  • getResponseCode 返回一个整数响应代码,所以我不确定如何将它与字符串进行比较。
  • 好的,所以你可以在你的服务器上创建一个文件日志并检查所有参数是否正确

标签: java android json api


【解决方案1】:

响应 403 表示您提交的凭据不正确或提交的凭据无效。因此,这里似乎有两个明显的地方可能会导致您的问题。

首先,您是否在替换点正确设置了登录名和 URL 密钥?

其次,您确定您是有效且有效的登录名和密钥吗?

【讨论】:

  • 是的,这是我检查的第一件事。正如我上面所说,使用相同的凭据,我可以从 chrome 中获得响应,但不能从代码中获得响应。
  • 我建议您放置一些日志语句来验证这一点。 403 的原因相当明确
  • 有没有办法指定 get 请求是通过 HTTP/1.1 发出的?
  • 为了返回 403,您必须已经成功建立了 HTTP 连接。我告诉你你没有正确提交你的信用。
  • 如果我没有正确传递凭据,那么当我使用相同的 url 格式和凭据从 chrome 请求时,我不应该得到相同的错误代码吗?
猜你喜欢
  • 2012-06-28
  • 1970-01-01
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多