简体   繁体   English

使用 volley (JAVA) 在 Android Studio 中调用 API

[英]API Call in Android Studio using volley (JAVA)

I am not sure what I am doing wrong.我不确定我做错了什么。 I am very new to this and just jumped straight into trying to make API calls.我对此很陌生,只是直接尝试进行 API 调用。 I am trying to retrieve information from rapidAPI for a simple project I am working on to view prices of stocks and so on.我正在尝试从 RapidAPI 检索信息,用于我正在处理的一个简单项目,以查看股票价格等。 I am using the volley package from Android Studio to make my APIcalls to retrieve JSON and trying to put that into a textView.我正在使用 Android Studio 中的 volley 包使我的 APIcalls 检索 JSON 并尝试将其放入 textView。 The way I imagine this to work is that I press a button and then once that is clicked, it runs the code to get the information and then shows the response in the textView.我想象这个工作的方式是我按下一个按钮,然后一旦被点击,它就会运行代码来获取信息,然后在 textView 中显示响应。 however, when the button is clicked, nothing happens.但是,当单击按钮时,什么也没有发生。 no error or response of any sort.没有任何错误或响应。


    private TextView mTextViewResult;
    private RequestQueue mQueue;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextViewResult= findViewById(R.id.text_view_result);
        Button buttonParse= findViewById(R.id.button_parse);

        mQueue= Volley.newRequestQueue(this);

        buttonParse.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                jsonParse();
            }
        });

    }
    private void jsonParse(){
      String url="https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-quotes?region=CA&lang=en&symbols=VEQT.TO";
        JsonObjectRequest request= new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray= response.getJSONArray("result");

                    JSONObject result=jsonArray.getJSONObject(0);
                    int marketPrice= result.getInt("regularMarketPrice");

                    mTextViewResult.setText(String.valueOf(marketPrice));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mTextViewResult.setText("" +error.toString());
            }


        }){
            @Override
            public Map<String,String> getHeaders() throws AuthFailureError{
                Map<String,String> params= new HashMap<>();
                params.put("x-rapidapi-host", "apidojo-yahoo-finance-v1.p.rapidapi.com");
                params.put("x-rapidapi-key", "APIKEY");
                return params;
            }
        };
        mQueue.add(request);
    }
}

From what you've posted are you sure your x-rapidapi-key is APIKEY .根据您发布的内容,您确定您的x-rapidapi-keyAPIKEY Pretty sure that's the primary reason of your issue.很确定这是您问题的主要原因。 Only after you put a valid API key in your request header, will your API call return a proper expected response.只有在您的请求标头中放入有效的 API 密钥后,您的 API 调用才会返回正确的预期响应。

You can read how to generate the rapidapi key from their official docs here您可以在此处阅读如何从他们的官方文档中生成 Rapidapi 密钥

Currently the response you receive on api call using the wrong apikey is something like this:目前,您在使用错误的 apikey 调用 api 时收到的响应是这样的:

{
   "message": "Key doesn't exists"
}

Now in your java code you are looking for a JSONArray based on the key "result", while the response currently only has "message" being returned.现在,在您的 Java 代码中,您正在寻找基于键“result”的 JSONArray,而响应当前仅返回“message”。 That's the reason nothing happens, you can try finding the value in response for message and get the error messages if you wish.这就是什么都没发生的原因,您可以尝试查找响应消息的值,并根据需要获取错误消息。 Generate a valid rapidapi key and try again, Good luck!生成一个有效的 Rapidapi 密钥并重试,祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM