【问题标题】:Using Mashape APIs with Volley or HttpURLConnection将 Mashape API 与 Volley 或 HttpURLConnection 一起使用
【发布时间】:2016-09-12 16:53:14
【问题描述】:

谁能指出我正确的方向或演示如何在没有 Unirest 的情况下使用 API 密钥向 Mashape 发出请求?

我希望简单地使用 HttpURLConnection 类或 Android REST 库(如 OkHttp 或 Volley)向 Mashape API 发出 JSON 请求,但我不知道如何构造请求,或者如果不使用 Mashape 的 Unirest 甚至可能图书馆。

这是他们推荐的创建 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 自己表示应该避免在 Android 上使用 Unirest: Does anyone have an example of an android studio project that import Unirest via gradle?

在这个问题中,我实际上是在尝试使用与初学者相同的 api 和相同的情况: Trying to fetch JSON with Android using Unirest

【问题讨论】:

    标签: android android-studio mashape


    【解决方案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("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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      相关资源
      最近更新 更多