0

试图在一个似乎只接受使用Unirest的请求的android应用程序中使用这个“ Words API ” 。

“难以置信”的定义请求示例(由 api 指定):

HttpResponse<JsonNode> response = Unirest.get("https://wordsapiv1.p.mashape.com/words/incredible/definitions")
  .header("X-Mashape-Key", "**********apikey************")
  .header("Accept", "application/json")
  .asJson();

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. 是否有可能做到这一点?

4

2 回答 2

2

此代码未经测试,但可让您了解如何解决此问题。

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);
    }
}
于 2016-03-05T01:54:56.523 回答
1

我认为更好的解决方案是使用 Volley 库。看看我的解决方案,别忘了添加依赖: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("VolleyResponse", "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);
于 2016-12-15T08:19:56.607 回答