简体   繁体   中英

Whats wrong with this code? Whenever i try to click the button my application just stops responding? this is a post request code

Here is the my post request code. please help me debug this one. thanks. i can run my application but it doesnt give out errors.

public void ibutton4Click()
    {
           {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost("10.0.0.1/cgi-bin/ForwardPress.cgi");
                try {

                  HttpResponse response = client.execute(post);
                  BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                  String line = "";
                  while ((line = rd.readLine()) != null) {
                    System.out.println(line);
                  }

                } catch (IOException e) {
                    startActivity(new Intent(this,MainActivity.class));
                }
              }
    }

For more on NetworkOnMainThread error and why is it that way,
1. Responsive UI in design and interaction
2. More on the Adroid class
3. Useful SO link

To fetch the data in a separate thread,

1. Write custom Asynctasks :
AsyncTask Dev Reference
AsyncTask Android example

OR

2. Use something like AsyncHttpClient: http://loopj.com/android-async-http/
where you get onSuccess and onFailure methods to work with the response.

The option 2. is better if you just want to fetch data without doing anything else, and work on it, or save it. For the same, you need to parse the response first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM