Trying to use this "Words API" in an android application which only seems to accept requests using Unirest.
Request example for the definition of "incredible" (specified by api):
HttpResponse<JsonNode> response = Unirest.get("https://wordsapiv1.p.mashape.com/words/incredible/definitions")
.header("X-Mashape-Key", "**********apikey************")
.header("Accept", "application/json")
.asJson();
The trouble is implementing the unirest request with doInBackground
in AsyncTask
.
protected void OnPreExecute(){
json_url = "https://wordsapiv1.p.mashape.com/words/incredible/definitions";
//where does api key go?
}
protected String doInBackground(Void... params) {
try {
// unirest goes here but how?
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) !=null)
stringBuilder.append(JSON_STRING+"\n");
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
}catch (MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Not sure exactly how to structure the request within doInBackground
.
Is it possible to do this?
This code is not tested but to give you an idea on how you might solve this problem.
I think the better solution would be to use the Volley library. Take a look at my solution, don't forget to add a dependency:
compile 'com.android.volley:volley:1.0.0'
. If you need more information.