munish
munish

Reputation: 13

httpclient.execute not giving result neither exception

I have a method in Android calling a web service, mentioned below.

Now when my class is calling this method I am not able to see any exception and only till System.out.println("entered into call service method 2"); log. I can see at logcat states response = httpclient.execute(httppost); is not working and System.out.println("entered into call service method 3"); is not displaying at logcat neither any exception. Any idea why so? How to fix it?

           public void callService() throws Exception {
        System.out.println("entered into call service method");
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://localhost:81/a.php");
        HttpResponse response;
        System.out.println("entered into call service method 1");
        try{
            System.out.println("entered into call service method 2");
            **response = httpclient.execute(httppost);**
            System.out.println("entered into call service method 3");

Upvotes: 1

Views: 2989

Answers (1)

peekler
peekler

Reputation: 330

Do you call this function in a separate Thread / AsyncTask? I would also recommend to consider using Service if requests are often used in your app.

Here is a POST method, that works for me, but do not forget to call it asyncronously somehow:

public void executePost(String url, List<NameValuePair> postParams) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    InputStream is = null;
    try {
        httppost.setEntity(new UrlEncodedFormEntity(postParams));
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int inChar;
                while ((inChar = is.read()) != -1) {
                    bos.write(inChar);
                }

                String resp = bos.toString();
                // report back the resp e.g. via LocalBroadcast message 
            } else {
                // report back e.g. via LocalBroadcast message 
            }
        }
        else {
            // report back e.g. via LocalBroadcast message 
        }
    } catch (Exception e) {
            // report back the exception e.g. via LocalBroadcast message 
        // exception message: e.getMessage()
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Upvotes: 1

Related Questions