0

I have this class to make an HttpRequest:

public class httpHandler
{
    public String post(String posturl, String user, String mensaje)
    {
        try
        {
            HttpClient httpclient = new DefaultHttpClient();
            //Creamos el objeto de HttpClient que nos permitira conectarnos mediante peticiones http
            HttpPost httppost = new HttpPost(posturl);

            //El objeto HttpPost permite que enviemos una peticion de tipo POST a una URL especificada
            //AÑADIR PARAMETROS

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user",user));
            params.add(new BasicNameValuePair("texto",mensaje));

    //Una vez añadidos los parametros actualizamos la entidad de httppost, esto quiere decir en pocas palabras anexamos los parametros al objeto para que al enviarse al servidor envien los datos que hemos añadido
            httppost.setEntity(new UrlEncodedFormEntity(params));

            //Finalmente ejecutamos enviando la info al server
            HttpResponse resp = httpclient.execute(httppost);
            HttpEntity ent = resp.getEntity();/*y obtenemos una respuesta*/

            String text = EntityUtils.toString(ent);

            return text;
        }
        catch(Exception e)
        {
            return "error";
        }
    }
}

and here is how I use it on the main activity...

httpHandler handler = new httpHandler();
String txt = handler.post("http://www.prodemundial.comeze.com/insert_mensaje.php",campoNombre.getText().toString(),campoMensaje.getText().toString());

Toast toast = Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_SHORT);
toast.show();

and txt variable returns error and I really don't know why !...

I hope you can help me...

Thanks !!!

Akshay Soam
  • 1,580
  • 3
  • 21
  • 39
  • 1
    possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – 323go Oct 18 '14 at 16:43
  • You'll get a `NetworkOnMainThreadException` -- google it, or see the related question. – 323go Oct 18 '14 at 16:44
  • Can u provide LogCat? – romy_ngo Oct 18 '14 at 16:46
  • @323go is possiblly correct. We don't see where you call this but if you are calling it at main thread you will get NetworkOnMainThreadException. Try to call it from an AsynTask or a Thread. – Devrim Oct 18 '14 at 16:53
  • 1
    @aegean, it's invoked synchronously, with a Toast following immediately. It's executed on the main thread... if not, he'd get an exception attempting to modify the view (by generating the toast) off the ui thread. – 323go Oct 18 '14 at 16:54

0 Answers0