【发布时间】: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 返回一个整数响应代码,所以我不确定如何将它与字符串进行比较。
-
好的,所以你可以在你的服务器上创建一个文件日志并检查所有参数是否正确