0

I was trying to use the HttpRequest methods on java but it doesn't work, this is my code

package com.example.phpconnect;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class httpHandler {

public String post(String posturl){

    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(posturl);
        Log.w("Se envio","Fase 1");

        HttpResponse resp = httpclient.execute(httppost);
        HttpEntity ent = resp.getEntity();          
        Log.w("Se envio","Fase 2");

        String text = EntityUtils.toString(ent);
        Log.w("Se envio","Fase 3");
        return text;
    }
    catch(Exception e){
        Log.w("Se envio","Error");
        return "Error";
    }

}

}

It works fine up to the first log, then it throws the error, please some one know where the problem is? thanks!

user2212773
  • 128
  • 1
  • 3
  • 9
  • 2
    How about some details on what the exception is, like the stacktrace maybe. Tough to figure things out without that. – cmbaxter Jun 11 '13 at 00:15
  • I don't get that, I just have that code, and my MainActivity, do I have to post that code too? – user2212773 Jun 11 '13 at 00:18
  • 1
    Inside your catch block you need to log the stacktrace from the `Exception e`. I'm not an android person, but typically, you just do `e.printStackTrace` and this goes to `System.out`. If you can't do that, at least log the message from the `Exception` like so: `Log.w(e.getMessage());` – cmbaxter Jun 11 '13 at 00:20
  • In looking at the android Log API docs, you can log the stacktrace like so: `Log.w("httpHandler", e);` – cmbaxter Jun 11 '13 at 00:23
  • Can't see the error log, but I bet you're passing an invalid URL. It should be encoded. One way is `URI.encode(string)`. Oh, and love the title :) – Matt Jun 11 '13 at 00:35
  • this is what I get when I use Log.w("httpHandler", e); http://pastebin.com/DbHCPw2d – user2212773 Jun 11 '13 at 00:39

1 Answers1

0

NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread.

As correctly pointed out in comment by @EJP, will just try elaborating it.

HTTP Post request should not be executed in Main Thread. It needs to be run in background and for that you may use AsyncTask and execute it in doInBackground().

More details on Exception!

Divya Motiwala
  • 1,659
  • 1
  • 16
  • 24