androidasynchttpclientandroid-async-http

AsyncHttpClient is not calling my POST API


I'm new to Android, I'm using AsyncHttpClient to call a POST API. But the API is not even being called

Below is my code:

        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();
            }
        });
    `

Any hints of what I'm doing wrong??


Solution

  • Solved, it appear that the problem was in AndroidManifest.xml Since I'm using the internet and calling an external API, I had to add:

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

    And another thing. When working locally and testing using the emulator, we should write
    http://10.0.2.2:port-number/ instead of http://localhost:port-number/. Because android emulator runs in a virtual machine. Therefore, localhost will be emulator's own loopback address.