Mohamad Mousheimish
Mohamad Mousheimish

Reputation: 1705

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??

Upvotes: 1

Views: 384

Answers (2)

Mohamad Mousheimish
Mohamad Mousheimish

Reputation: 1705

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.

Upvotes: 1

Richa Shah
Richa Shah

Reputation: 984

Please put debugger at your method and Make sure its calling or not , I think you have passed wrong context value And as my point of View its better to User Retrofit than AsyncHttpClient. Use Retrofit if you are communicating with a Web service.

Upvotes: 0

Related Questions