2016-09-12 58 views
0

任何人都可以指向正確的方向,或者演示如何使用沒有Unirest的API密鑰向Mashape發出請求?在Volley或HttpURLConnection中使用Mashape API

我希望只需使用HttpURLConnection類或Android REST庫(如OkHttp或Volley)向Mashape API發出JSON請求,但我無法弄清楚如何構造請求,或者如果甚至可能不使用Mashape's不太好的圖書館。

這是他們如何推薦創建Unirest請求:

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

我試着避免Unirest,因爲它似乎是一個痛苦的設置和因爲偉大的CommonsWare自己說Unirest應避免爲Android: Does anyone have an example of an android studio project that import Unirest via gradle?

我實際上是試圖使用相同的API,並與相同的情況下爲初學者這樣一個問題: Trying to fetch JSON with Android using Unirest

回答

0

我相信,我的答案就是你要找的。

我用排槍庫,你需要添加一個依賴性: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); 
相關問題