-1

我很高兴我的问题是,我在 andriod 中使用 httpclient 我为我的应用程序授予了 Internet 权限,然后我运行我的应用程序并单击按钮,但不幸的是,它停止了。请帮我看看我的代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final   EditText user=(EditText) findViewById(R.id.username);
    final   EditText pass=(EditText) findViewById(R.id.password);
    Button login=(Button) findViewhere`ById(R.id.login);
    login.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            String u=user.getText().toString();
            String p=pass.getText().toString();
            HttpClient httpClient=new DefaultHttpClient();
            HttpPost httppost=new HttpPost("http://202.164.53.122");
            BasicNameValuePair usernameBaseNameValuePair=new BasicNameValuePair("id",u);
            BasicNameValuePair passBaseNameValuePair=new BasicNameValuePair("pass",p);
            List<NameValuePair> nameValuePairList=new ArrayList<NameValuePair>();
            nameValuePairList.add(usernameBaseNameValuePair);
            nameValuePairList.add(passBaseNameValuePair);
            try {
                UrlEncodedFormEntity urlEncodedFormEntity=new 
                UrlEncodedFormEntity(nameValuePairList,HTTP.UTF_8);
                httppost.setEntity(urlEncodedFormEntity);
                try {
                    HttpResponse httpResponse=httpClient.execute(httppost);
                } catch (ClientProtocolException e) {
                } catch (IOException e) {
                user.setText(e.getMessage());
                }

            }catch(UnsupportedEncodingException uee){
            }
        }
    });
}

@Override

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
4

5 回答 5

0

如果您在 android 4.0+ 中使用此代码,则会出现异常android.os.NetworkOnMainThreadException。使用AsyncTask提供任何 http 通信。

于 2013-09-08T08:18:09.627 回答
0

首先,创建一个单独的类来获取请求并使用 Asynctask 执行所有操作。使用 String 传递 URI,然后在 Asynctask 中传递 URI。此方法不会阻塞您的主 UI 线程。
请参阅此链接了解如何使用 Asynctask。 http://developer.android.com/reference/android/os/AsyncTask.html

于 2013-09-08T08:23:58.370 回答
0

对于网络操作,您应该使用不同的线程而不是使用主线程,因为在主线程上使用网络会导致应用程序 UI 无响应以避免这种情况,您应该使用AyncTask 例如 AsyncTask 使用此链接

于 2013-09-08T08:26:09.270 回答
0

不要在主线程(或 get android.os.NetworkOnMainThreadException)上使用网络。使用thread classAsyncTask class
异步任务
线程

于 2013-09-08T09:27:22.843 回答
0

首先,您应该使用不同的线程来发送请求。或者,最好的方法是使用带有 post 方法的 volley requests。它更快、更高效。

于 2016-11-22T14:12:40.517 回答