本文介绍了尝试使用Unirest在Android上获取JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在 android 应用程序中使用此" Words API ",该应用程序似乎只接受使用 Unirest 的请求.

Trying to use this "Words API" in an android application which only seems to accept requests using Unirest.

"incredible"(由api指定)定义的请求示例:

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();

麻烦的是在AsyncTask中用doInBackground来实现unirest请求.

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;
    }

不确定确切如何在doInBackground中构造请求.是否有可能做到这一点?

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.

private class TastingUniRestAsync extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... urls) {
        String pathToFile = urls[0];
        String responseResult = "";
        HttpResponse<JsonNode> response = Unirest.get(pathToFile)
                .header("X-Mashape-Key", "**********apikey************")
                .header("Accept", "application/json")
                .asJson();

        if(null != response){
            //convert your response to the data type you want. Here I am using string
            responseResult = //assign the manipulated Json string;
        }
        return responseResult
    }
    protected void onPostExecute(String responseResult){
        // You can assign it to TextView widget for example
        mTextView.setText(responseResult);
    }
}

这篇关于尝试使用Unirest在Android上获取JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 06:50