AsyncHttpClient没有调用我的POST API

问题描述 投票:0回答:2

我是Android的新手,我正在使用AsyncHttpClient来调用POST API。但API甚至没有被调用

以下是我的代码:

        AsyncHttpClient client = new AsyncHttpClient();

        client.addHeader("Key","random-key");
        JSONObject body = new JSONObject();
        body.put("clientId","random-client-id");
        body.put("question",question);
        HttpEntity entity = new StringEntity(body.toString());
        client.post( getApplicationContext(),"http://localhost:3000/api/Chats/GetAnswer", entity,"application/json", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                List<List<Answer>> answers = new ArrayList<>();
                try {
                    JSONArray answersJson = response.getJSONArray("answers");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String response, Throwable error) {
                Toast toast = Toast.makeText(getApplicationContext(),"Unable to get answers for the question sent",Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    `

我做错了什么提示?

android asynchttpclient android-async-http
2个回答
0
投票

解决了,问题出现在AndroidManifest.xml因为我正在使用互联网并调用外部API,所以我不得不补充:

<uses-permission android:name="android.permission.INTERNET"/>

另一件事。在本地工作并使用模拟器进行测试时,我们应该写 http://10.0.2.2:port-number/而不是http://localhost:port-number/。因为android模拟器在虚拟机中运行。因此,localhost将是模拟器自己的环回地址。


-1
投票

请把调试器放在你的方法上并确保它的调用与否,我认为你已经传递了错误的上下文值而且我的观点比使用AsyncHttpClient更好的用户改造。如果要与Web服务通信,请使用Retrofit。

© www.soinside.com 2019 - 2024. All rights reserved.