简体   繁体   中英

Connect Android App to restful webservice

I know this has been asked quite a lot of times, but i cant find a proper answer to my question and hope one of you can help me out ;-)

I'm trying to communicate to a rest webservice with an android app on a smartphone device (so no emulator). The webservice is running on 192.168.0.2:8080 on a windows machine. The device is connected in the same wlan network as the pc. When im opening the link with the device's chrome browser, the webservice responds normally.

Here's the code i use to connect to the webservice in a AsyncTask:

    protected Integer doInBackground(String... params)
    {
        try
        {
            AndroidHttpClient client = AndroidHttpClient.newInstance("androidClient", getContext());
            HttpPost post = new HttpPost(params[0]);
            String xml = new ScoreDto(new Random(System.currentTimeMillis()).nextLong()).toXml();
            post.setEntity(new StringEntity(xml));
            return client.execute(post).getStatusLine().getStatusCode();
        }
        catch (Exception e)
        {
            Log.e(TAG, e.getLocalizedMessage());
            return 0;
        }
    }
  • I used several different approaches on trying to connect, always resulting in a connection timeout
  • I included the internet permission in my app.
  • I deactivated the local firewall on the windows pc for the time being.
  • I tried port forwarding for the device
  • I tried calling a different webservice from within the app httpbin.org/ip and get a valid response.

Any ideas? The problem seems to be connected to the local network.. Are there special limitations or permissions needed if i want to connect to an external server via my android device? Thanks in advance ;-)

Thanks for everyone who posted a comment trying to help.
I figured out what was wrong:
The post request was missing a content-type header...

A fully functioning doBackground -Implementation would look as follows:

protected Integer doInBackground(String... params)
{
    try
    {
        //TODO check if params.length >=2 & not empty
        AndroidHttpClient client = AndroidHttpClient.newInstance("androidClient", getContext());
        HttpPost post = new HttpPost(params[0]);
        post.setHeader("content-type", "application/xml");
        post.setEntity(new StringEntity(params[1]));
        return client.execute(post).getStatusLine().getStatusCode();
    }
    catch (Exception e)
    {
        Log.e(TAG, e.getLocalizedMessage());
        return 0;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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