本文介绍了将Mashape API与Volley或HttpURLConnection一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

Can anyone point me in the right direction or demonstrate how to make a request to Mashape using an API key without Unirest?

我希望仅使用HttpURLConnection类或也许使用OkHttp或Volley之类的Android REST库向Mashape API发出JSON请求,但我无法弄清楚如何构造该请求,或者甚至可以在不使用Mashape的Unirest的情况下实现该请求图书馆.

I hope to make a JSON request to a Mashape API simply using the HttpURLConnection class or perhaps Android REST libraries like OkHttp or Volley, but I cant figure out how to structure the request, or if it is even possible without using Mashape's Unirest library.

这是他们建议创建Unirest请求的方式:

This is how they recommend to create Unirest requests:

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:任何人都有通过gradle导入Unirest的android studio项目的示例?

Im trying to avoid Unirest because it seems like a pain to set up and because the great CommonsWare himself stated Unirest should be avoided for Android:Does anyone have an example of an android studio project that import Unirest via gradle?

实际上,我在这个问题中尝试使用与初学者相同的api,并在相同的情况下使用:尝试使用Unirest在Android上获取JSON

I am actually trying to use the same api and with the same circumstances as Beginner in this question:Trying to fetch JSON with Android using Unirest

推荐答案

我相信,我的答案就是您要寻找的东西.

I believe, my answer is what you are looking for.

我使用了Volley库,您需要添加一个依赖项:compile 'com.android.volley:volley:1.0.0'

I used Volley library, you need to add a dependency: 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);

这篇关于将Mashape API与Volley或HttpURLConnection一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 13:46