kramer65
kramer65

Reputation: 53873

POST request from within Android app returns a Connection refused, but it works form the browser

From within my Android app I'm trying to make a POST request to an API which I built using Flask. The API works using the following message from the Postman REST-Client:

POST /api/message/1 HTTP/1.1
Host: 10.0.0.10:5000
Content-Type: application/json
Accept-Encoding: application/json
Cache-Control: no-cache

{"text": "This is a message"}

This works correctly and returns {"testkey": "testmessage"} just as expected. I now make a call from within my Android app using the following AsyncTask:

private class SendMessageTask extends AsyncTask<String, Integer, Boolean> {
    protected Boolean doInBackground(String... messages) {

        HttpPost post = new HttpPost("http://10.0.0.10/api/message/1");
        post.setHeader("Content-Type", "application/json");
        post.setHeader("Accept-Encoding", "application/json");
        HttpClient client = new DefaultHttpClient();

        JSONObject json = new JSONObject();

        try {
            json.put("text", messages);
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }

        try {
            post.setEntity(new StringEntity(json.toString()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }

        try {
            client.execute(post);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}

I simply call this using new SendMessageTask().execute(message.text);. This however, gives an error saying org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.0.10:5000 refused.

When I simply type in the same url in the browser of my phone I get the expected response (I know that's a GET, but I don't even check for GET or POST on the API side yet).

Does anybody know what I'm doing wrong here? All tips are welcome!

Upvotes: 0

Views: 533

Answers (1)

Sameer
Sameer

Reputation: 2171

<uses-permission android:name="android.permission.INTERNET"/> add this tag into AndroidManifest.xml of your Android project.

Upvotes: 2

Related Questions