问题
Can anyone point me in the right direction or demonstrate how to make a request to Mashape using an API key without Unirest?
I hope to make a JSON request to a Mashape API simply using the HttpURLConnection class or perhaps Android REST libraries like OkHttp or Volley, but I cant figure out how to structure the request, or if it is even possible without using Mashape's Unirest library.
This is how they recommend to create Unirest requests:
HttpResponse<JsonNode> response = Unirest.get("https://wordsapiv1.p.mashape.com/words/incredible/definitions")
.header("X-Mashape-Key", "**********apikey************")
.header("Accept", "application/json")
.asJson();
Im trying to avoid Unirest because it seems like a pain to set up and because the great CommonsWare himself stated Unirest should be avoided for Android: Does anyone have an example of an android studio project that import Unirest via gradle?
I am actually trying to use the same api and with the same circumstances as Beginner in this question: Trying to fetch JSON with Android using Unirest
回答1:
I believe, my answer is what you are looking for.
I used Volley library, you need to add a dependency: compile 'com.android.volley:volley:1.0.0'
RequestQueue requestQueue = Volley.newRequestQueue(this);
String uri = Uri.parse("https://wordsapiv1.p.mashape.com/words/incredible/definitions")
.buildUpon()
.build().toString();
StringRequest stringRequest = new StringRequest(
Request.Method.GET, uri, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("MainActivity", "response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VolleyError", error.toString());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("X-Mashape-Key", "<API_KEY>");
params.put("Accept", "text/plain");
return params;
}
};
requestQueue.add(stringRequest);
来源:https://stackoverflow.com/questions/39455168/using-mashape-apis-with-volley-or-httpurlconnection