我已经有一个应用程序,它使用api的加载器,但是我想让它适应新的API。问题是新api是以这种格式给我的:
curl -H "Authorization: Token <myToken>" "https://localelections.usvotefoundation.org/api/v1/states"
我可以在终端中使用得很好,但我不知道如何在Android Studio中使用它。任何人都可以指出我正确的方向吗?
我的Utils文件中的一些代码:
// Returns new URL object from the given string URL.
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
//Make an HTTP request to the given URL and return a String as the response.
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) 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 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;
}
答案 0 :(得分:1)
您需要使用Authorization
这样将HttpURLConnection
设置为标题。
urlConnection.setRequestProperty ("Authorization", yourTokenHere);