Http Request错误无法在未调用Looper.prepare()的线程内创建处理程序

时间:2014-12-31 21:55:21

标签: java android http

我正在尝试发布http请求,我使用线程和asyncTask来避免这种错误

Caused by: android.os.NetworkOnMainThreadException

但是我收到了新的错误:

Can't create handler inside thread that has not called Looper.prepare()

当我使用此代码时

 Thread th = new Thread(new Runnable() {
        @Override
        public void run() {

            Toast.makeText(MainActivity.this,"loop",Toast.LENGTH_LONG).show();
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost("https://api.twitter.com/1.1/statuses/update.json");
            post.setHeader("Authorization","OAuth realm=\"https://api.twitter.com/1.1/statuses/update.json\",status=\"aay%20from%20pstman8\",oauth_consumer_key=\"xx\",oauth_token=\"xx\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1420004144\",oauth_nonce=\"2neFPPabcd2neFPPabcd2neFPPabcdqq\",oauth_version=\"1.0\",oauth_signature=\"ZbexXD3Npgy6pzQ3u3mnbDNFHcw%3D\"");
            try
            {

                client.execute(post);
                Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show();

            }
            catch(IOException e)
            {
                Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    });

2 个答案:

答案 0 :(得分:1)

您收到此错误是因为您尝试显示来自辅助线程的Toast消息。

请从UI线程调用Toast.makeText:

activity.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
  }
});

答案 1 :(得分:0)

对于简单的HTTP请求,避免使用像这样的纯线程,你有很多选择,如果你正在编写一个可以进行多次http调用的应用程序,我建议你使用一些第三方网络库。一开始,不花任何时间自己开发它。例如,看看Volley for Android。如果您只想进行一次性调用,请使用AsyncTask,如下所示:

public class MyTwitterCall extends AsyncTask<Void, Void, {needed data}> { 
     @Override
     protected {needed data} doInBackground(Void... params) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("https://api.twitter.com/1.1/statuses/update.json");
        post.setHeader("Authorization","OAuth realm=\"https://api.twitter.com/1.1/statuses/update.json\",status=\"aay%20from%20pstman8\",oauth_consumer_key=\"xx\",oauth_token=\"xx\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1420004144\",oauth_nonce=\"2neFPPabcd2neFPPabcd2neFPPabcdqq\",oauth_version=\"1.0\",oauth_signature=\"ZbexXD3Npgy6pzQ3u3mnbDNFHcw%3D\"");
       //TODO Execute call and extract response to {needed data}
    return {needed data}
}

然后从您的活动或片段调用: new MyTwitterCall().execute();