在android中使用url登录时出错

时间:2012-09-18 04:14:01

标签: android url login httpclient

我遵循本教程并收到错误Android Login Screen Using HttpClient

为什么我无法登录?我的targetversion是targetSdkVersion 15和minSdkVersion 12.按下按钮登录时出错。

MainActivity

public class MainActivity extends Activity implements OnClickListener {

Button ok, back, exit;
TextView result;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ok = (Button) findViewById(R.id.btn_login);
    ok.setOnClickListener(this);
    result = (TextView) findViewById(R.id.lbl_result);
}

public void postLoginData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.sencide.com/blog/login.php");

    try {
        EditText uname = (EditText) findViewById(R.id.txt_username);
        String username = uname.getText().toString();

        EditText pword = (EditText) findViewById(R.id.txt_password);
        String password = pword.getText().toString();

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username", username));
        nameValuePairs.add(new BasicNameValuePair("password", password));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        Log.w("SENCIDE", "Execute HTTP Post Request");
        HttpResponse response = httpclient.execute(httppost);

        String str = inputStreamToString(response.getEntity().getContent()).toString();
        Log.w("SENCIDE", str);

        if (str.toString().equalsIgnoreCase("true")) {
            Log.w("SENCIDE", "TRUE");
            result.setText("Login successful");
        } else {
            Log.w("SENCIDE", "FALSE");
            result.setText(str);
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private StringBuilder inputStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return total;
}

public void onClick(View view) {
    if (view == ok) {
        postLoginData();
    }
  }
}

ERROR

09-18 10:50:40.531: E/AndroidRuntime(23081): FATAL EXCEPTION: main
09-18 10:50:40.531: E/AndroidRuntime(23081): android.os.NetworkOnMainThreadException
09-18 10:50:40.531: E/AndroidRuntime(23081):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at java.net.InetAddress.getAllByName(InetAddress.java:220)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at com.example.login.MainActivity.postLoginData(MainActivity.java:63)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at com.example.login.MainActivity.onClick(MainActivity.java:101)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at android.view.View.performClick(View.java:3558)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at android.view.View$PerformClick.run(View.java:14157)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at android.os.Handler.handleCallback(Handler.java:605)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at android.os.Looper.loop(Looper.java:137)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at android.app.ActivityThread.main(ActivityThread.java:4514)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at java.lang.reflect.Method.invokeNative(Native Method)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at java.lang.reflect.Method.invoke(Method.java:511)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
09-18 10:50:40.531: E/AndroidRuntime(23081):    at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:1)

仅供参考,NetworkOnMainThreadException可从API 11获得,如果您在主线程本身内部进行长时间运行任务,则不会允许您这样做。

要解决上述问题,请尝试在AsyncTask doInBackground() 方法中进行网络服务调用或长时间运行的任务。仅供参考,其在Android中为Painless Threading

例如:

doInBackground()中调用 postData()方法,并根据按钮单击执行此AsyncTask类。

答案 1 :(得分:0)

不要在主UI线程中编写网络调用。而不是使用asynctask或其他。

答案 2 :(得分:0)

解决这个问题的两个方法。

1)不要在主UI线程中编写网络调用,为此使用异步任务。

2)在setContentView(R.layout.activity_main);

之后,将以下代码写入MainActivity文件
if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}