Error while running an Httpresponse in Android Studio

Asked

Viewed 281 times

0

I am trying to send a string from an Android app to a PHP page, but when I send it, an error occurs in the method

Httpresponse Response=httpclient.execute(httppost);

In case anyone can help me with any information to try to solve this problem, I thank you in advance!

I have done a good search on the internet and one of the most valid ways I found for my situation was this method below

reference: 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());
    }

}

And this is the code I made to receive String.

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

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

Thank you for your attention.

  • What mistake happens? what he says?

  • it gives the error of catch (Exception e) { Log. e("log_tag", "Error in http Connection " + e.toString()); } when it arrives at this method Httpresponse Sponse = httpclient.execute(httppost);

  • What message?

  • 1

    E/log_tag: Error in http Connection android.os.Networkonmainthreadexception

  • Onmainthreadexception means that you cannot run httpclient on the main thread. To do this create a AsyncTask and execute your code within Asynctask

  • Thanks guys, I’ll search a way to do with Async Task and see if it works. anything I come back here. Valew support you!!

  • Unfortunately I can only test tomorrow, but that error is really gone, Thank you very much for the help :D :)

  • 1
Show 3 more comments

1 answer

1


Get out of here! working!!!

I made some changes in the scope and used some tips provided by Leosantana and it worked here

the code went like this

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) {
    }
}

Thanks for the help :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.