首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将Mashape API与Volley或HttpURLConnection配合使用

将Mashape API与Volley或HttpURLConnection配合使用
EN

Stack Overflow用户
提问于 2016-09-13 00:53:14
回答 1查看 691关注 0票数 0

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

我希望简单地使用HttpURLConnection类或者像OkHttp或Volley这样的Android REST库来向Mashape API发出一个JSON请求,但是我不知道如何构造这个请求,或者如果不使用Mashape的Unirest库,这是否可能。

下面是他们推荐的创建Unirest请求的方法:

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

我试图避免使用Unirest,因为它看起来设置起来很痛苦,而且因为伟大的安卓自己也声明应该避免使用Unirest:Does anyone have an example of an android studio project that import Unirest via gradle?

在这个问题中,我实际上正在尝试使用与初学者相同的应用程序接口和环境:Trying to fetch JSON with Android using Unirest

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-15 16:14:51

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

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

代码语言:javascript
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39455168

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档