0

estou tentando enviar uma string de um aplicativo Android para uma página PHP, porem, quando realizo o envio, ocorre um erro no método

HttpResponse response=httpclient.execute(httppost);

Caso alguém possa me ajudar com qualquer informação pra tentar resolver este problema, agradeço desde já!

Já realizei uma boa pesquisa na internet e uma das formas mais válidas que encontrei para minha situação foi este método abaixo

referencia: https://stackoverflow.com/questions/16079991/send-a-string-on-android-with-httppost-without-using-namevaluepairs

public void postData0(View v){
    try {
        Log.v("GG", "Sending sever 1 - try");
        // start - line is for sever connection/communication
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://meuSite.com.br/listener.php");

        httppost.setEntity(new StringEntity("legume = batata"));

        Log.v("GG", "erro ocorre na linha abaixo. . .");

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        // end - line is for sever connection/communication
        InputStream is = entity.getContent();
        Toast.makeText(getApplicationContext(),
                "Send to server and inserted into mysql Successfully", Toast.LENGTH_LONG)
                .show();
        // Execute HTTP Post Request
        response= httpclient.execute(httppost);
        entity = response.getEntity();
        String getResult = EntityUtils.toString(entity);
        Log.e("response =", " " + getResult);



    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection "
                + e.toString());
    }

}

E este é o código que fiz para receber a String.

$tudo = $_REQUEST['legume'];
var_dump($tudo);

$fp = fopen('teste/teste.txt', 'w');
fwrite($fp, $tudo);

Obrigado pela atenção.

8
  • Qual erro acontece? o que ele diz?
    – rray
    5/11/2015 às 17:55
  • ele da o erro do catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } quando chega neste método HttpResponse response = httpclient.execute(httppost); da o erro 5/11/2015 às 18:16
  • Qual é mensagem?
    – rray
    5/11/2015 às 18:21
  • 1
    E/log_tag: Error in http connection android.os.NetworkOnMainThreadException 5/11/2015 às 18:25
  • 1
    Relacionado Erro NetworkOnMainThreadException usando HTTPClient
    – ramaral
    5/11/2015 às 22:32

1 Resposta 1

1

Dalhe galera!! a funcionando!!!

fiz algumas alterações no escopo e utilizei algumas dicas fornecidas pelo LeoSantana e deu certo aqui

o código ficou assim

public void postData0(View v){new LongOperation().execute("");}


private class LongOperation extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        try {
            Log.v("GG", "Sending sever 1 - try");
            // start - line is for sever connection/communication
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://meuSite.com.br/listener.php");

            //httppost.setEntity(new StringEntity("legume = batata"));
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("legume", "{\"usuario\":[{\"nome\":\"fulano\",\"idade\":\"97\",\"email\":\"[email protected]\", \"sexo\":\"masculino\"}]}"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            Log.v("GG", "erro ocorre na linha abaixo. . .");

            HttpResponse response = httpclient.execute(httppost);
            Log.v("GG", ":D :D :D . . .");
            HttpEntity entity = response.getEntity();
            Log.v("GG", "1 . . .");
            // end - line is for sever connection/communication
            InputStream is = entity.getContent();
            Log.v("GG", "2 . . .");
            //Toast.makeText(getApplicationContext(),
            //      "Send to server and inserted into mysql Successfully", Toast.LENGTH_LONG)
            //      .show();
            // Execute HTTP Post Request
            response= httpclient.execute(httppost);
            entity = response.getEntity();
            String getResult = EntityUtils.toString(entity);
            Log.e("response =", " " + getResult);



        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection "
                    + e.toString());
        }


        return null;
    }

    @Override
    protected void onPostExecute(String result) {
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

Obrigado pela ajuda :D

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .