java - 尝试使用 HTTPPost 和 HTTPGet 在 Android 中创建登录应用程序,但登录已停止

标签 java android http

    package com.example.login;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;

    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v7.app.ActionBarActivity;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.EditText;
    import android.widget.Toast;

    public class Testcase extends ActionBarActivity {
    EditText user;
    EditText pass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testcase);
        user = (EditText) this.findViewById(R.id.editText1);
        pass = (EditText) this.findViewById(R.id.editText2);


    }

    //When login button is pressed
    public void xxx(View view) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://www.masterkool.com/callcenter/index.php");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("a_user", user.getText()
                .toString()));
        nameValuePairs.add(new BasicNameValuePair("a_pass", pass.getText()
                .toString()));

        try {

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse execute = httpclient.execute(httppost);
            InputStream content;
            content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(
                    content));
            String s = "";
            String test = "";
            while ((s = buffer.readLine()) != null) {
                test += s;
            }
            if (test.contains("U")) {
                // reset field and toast
                Toast.makeText(getBaseContext(), "Login Failed",     Toast.LENGTH_SHORT)
                        .show();
            } else {
                // Intent intent = new Intent(MainActivity.this,Form.class);
                // this.startActivity(intent);
                Toast.makeText(getBaseContext(), "Login Successful",
                        Toast.LENGTH_SHORT).show();
            }
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.testcase, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

包含简单 View 的占位符 fragment 。

这是日志猫:

 06-10 13:42:29.670: E/AndroidRuntime(797): FATAL EXCEPTION: main
06-10 13:42:29.670: E/AndroidRuntime(797): Process: com.example.login,
PID: 797 06-10 13:42:29.670: E/AndroidRuntime(797):
java.lang.IllegalStateException: Could not execute method of the
activity 06-10 13:42:29.670: E/AndroidRuntime(797):     at
android.view.View$1.onClick(View.java:3823) 06-10 13:42:29.670:
E/AndroidRuntime(797):  at
android.view.View.performClick(View.java:4438) 06-10 13:42:29.670:
E/AndroidRuntime(797):  at
android.view.View$PerformClick.run(View.java:18422) 06-10
13:42:29.670: E/AndroidRuntime(797):    at
android.os.Handler.handleCallback(Handler.java:733) 06-10
13:42:29.670: E/AndroidRuntime(797):    at
android.os.Handler.dispatchMessage(Handler.java:95) 06-10
13:42:29.670: E/AndroidRuntime(797):    at
android.os.Looper.loop(Looper.java:136) 06-10 13:42:29.670:
E/AndroidRuntime(797):  at
android.app.ActivityThread.main(ActivityThread.java:5017) 06-10
13:42:29.670: E/AndroidRuntime(797):    at
java.lang.reflect.Method.invokeNative(Native Method) 06-10
13:42:29.670: E/AndroidRuntime(797):    at
java.lang.reflect.Method.invoke(Method.java:515) 06-10 13:42:29.670:
E/AndroidRuntime(797):  at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-10 13:42:29.670: E/AndroidRuntime(797):  at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 06-10
13:42:29.670: E/AndroidRuntime(797):    at
dalvik.system.NativeStart.main(Native Method) 06-10 13:42:29.670:
E/AndroidRuntime(797): Caused by:
java.lang.reflect.InvocationTargetException 06-10 13:42:29.670:
E/AndroidRuntime(797):  at
java.lang.reflect.Method.invokeNative(Native Method) 06-10
13:42:29.670: E/AndroidRuntime(797):    at
java.lang.reflect.Method.invoke(Method.java:515) 06-10 13:42:29.670:
E/AndroidRuntime(797):  at android.view.View$1.onClick(View.java:3818)
06-10 13:42:29.670: E/AndroidRuntime(797):  ... 11 more 06-10
13:42:29.670: E/AndroidRuntime(797): Caused by:
android.os.NetworkOnMainThreadException 06-10 13:42:29.670:
E/AndroidRuntime(797):  at
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
06-10 13:42:29.670: E/AndroidRuntime(797):  at
java.net.InetAddress.lookupHostByName(InetAddress.java:385) 06-10
13:42:29.670: E/AndroidRuntime(797):    at
java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 06-10
13:42:29.670: E/AndroidRuntime(797):    at
java.net.InetAddress.getAllByName(InetAddress.java:214) 06-10
13:42:29.670: E/AndroidRuntime(797):    at
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
06-10 13:42:29.670: E/AndroidRuntime(797):  at
org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-10 13:42:29.670: E/AndroidRuntime(797):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-10 13:42:29.670: E/AndroidRuntime(797):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
06-10 13:42:29.670: E/AndroidRuntime(797):  at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-10 13:42:29.670: E/AndroidRuntime(797):  at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-10 13:42:29.670: E/AndroidRuntime(797):  at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-10 13:42:29.670: E/AndroidRuntime(797):  at
com.example.login.Testcase.xxx(Testcase.java:57) 06-10 13:42:29.670:
E/AndroidRuntime(797):  ... 14 more

最佳答案

Web 服务调用往往会消耗时间,从而阻塞 UI 线程,因此不应从主线程调用。作为最佳实践,Web 服务调用应始终仅从 AsyncTask 调用。

下面是未经测试的代码。希望您对 AsyncTask 有一个合理的了解使用此代码。

public class MainActivity extends Activity
{   
@Override
protected void onCreate(Bundle savedInstanceState) 
{
    .... // Some code here
    // Async task can also be called from within an onclick code.
    new AsyncTaskOperation().execute("");
}


/* Async Task called to avoid Android Network On Main Thread Exception. Web services need to be consumed only in background.     */
private class AsyncTaskOperation extends AsyncTask <String, Void, Void>
{

    private ProgressDialog Dialog = new ProgressDialog(LoginActivity.this);
     String ciao="";
    protected void onPreExecute() {
        // Display the loading spinner
        Dialog.setMessage("Loading... Please wait.. ");
        Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        Dialog.setInverseBackgroundForced(false);
        Dialog.setCancelable(false);
        Dialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.progressbar_new));

        Dialog.show();
    }

    @Override
    protected Void doInBackground(String... paramsObj) {
       HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://www.masterkool.com/callcenter/index.php");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("a_user", user.getText()
            .toString()));
    nameValuePairs.add(new BasicNameValuePair("a_pass", pass.getText()
            .toString()));

    try {

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse execute = httpclient.execute(httppost);
        InputStream content;
        content = execute.getEntity().getContent();
        BufferedReader buffer = new BufferedReader(new InputStreamReader(
                content));
        String s = "";
        String test = "";
        while ((s = buffer.readLine()) != null) {
            test += s;
        }
        if (test.contains("U")) {
            // reset field and toast
            Toast.makeText(getBaseContext(), "Login Failed",     Toast.LENGTH_SHORT)
                    .show();
        } else {
            // Intent intent = new Intent(MainActivity.this,Form.class);
            // this.startActivity(intent);
            Toast.makeText(getBaseContext(), "Login Successful",
                    Toast.LENGTH_SHORT).show();
        }
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
        return null;
    }

    protected void onPostExecute(Void unused) 
    {
        // Close progress dialog
        Dialog.dismiss();
        // Do actions after end of the HTTPGet or POST Method

    } // End of method onPostExecute

} // End of class AsyncTaskOperation

} End of MainActivity

关于java - 尝试使用 HTTPPost 和 HTTPGet 在 Android 中创建登录应用程序,但登录已停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24154372/

相关文章:

java - 无法在 android TextView 中打印 JSON 对象字符串

java - Eclipse-Tomcat 设置中的错误 - ClassNotFoundException "1catalina.org.apache.juli.FileHandler"

java - 如何从ArrayList中获取Point值

c - 什么是 HTTP Parser,用在什么地方,有什么作用

http - org.apache.cxf.transport.http.HTTPException : HTTP response '415

ios - 为 iOS 发送多个 HTTP Post 请求的最快方法?

java - 如何解决 wsdl2java 上 ObjectFactory 中的冲突?

java - 环境变量无法识别

android - AlarmManager PendingIntent.FLAG_NO_CREATE 取消警报后返回不为空

android - 在android中解析多个Json对象