Android Post请求失败

时间:2014-09-21 12:52:04

标签: php android

两天以来我的android项目已经出现问题了。 我实现了身份验证测试。我的类从editText接收一个数字,然后将此问题带回到php脚本,该脚本负责检查数据库中是否收到该号码。

这是我的班级

package com.androidproject.myFirstApp;

import android.app.Activity;
import android.app.AlertDialog;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
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 org.json.JSONObject;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity
{
    EditText inputpinCode;
    CheckBox checkBox;
    Button btnLogin;


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

        setTitle("Welcome");


        inputpinCode = (EditText) findViewById(R.id.loginpinCode);
        checkBox = (CheckBox)findViewById(R.id.cbRememberMe);
        btnLogin = (Button) findViewById(R.id.btnLogin);


        SharedPreferences pref = getSharedPreferences(PREFS_NOM,MODE_PRIVATE); 
        String pinCode = pref.getString(PREF_pinCode, "");
        String checked = pref.getString(PREF_CHECKED, "");

        inputpinCode.setText(pinCode);
        checkBox.setChecked(Boolean.parseBoolean(checked));


        btnLogin.setOnClickListener(new View.OnClickListener() 
        {           
            public void onClick(View view) 
            {

                boolean error = true;
                @SuppressWarnings("unused")
                long val = 0;
                String pinCode = inputpinCode.getText().toString(); 
                if (!TextUtils.isEmpty(pinCode)) {
                    try {
                        val = Long.valueOf(pinCode);
                        error = false;
                    }
                    catch(NumberFormatException e) {
                        Log.w("Error", e);
                    }
                }
                if (error) {                  
                    Toast.makeText(getBaseContext(),"Please enter your pin code.",Toast.LENGTH_SHORT).show();
                }else{

                    if ((pinCode != null) && (pinCode.trim().length() == 8)) {

                        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                        nameValuePairs.add(new BasicNameValuePair("tag", "login"));
                        nameValuePairs.add(new BasicNameValuePair("pinCode", pinCode));

                        try
                        {
                            Boolean isInternetPresent = false;
                            ConnectionDetector cd;

                            cd = new ConnectionDetector(getApplicationContext());
                            isInternetPresent = cd.isConnectingToInternet();
                            if (isInternetPresent) {                        

                            HttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new HttpPost("http://matanddin.zz.mu/android_app/auth.php");
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            HttpResponse response = httpclient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            InputStream is = entity.getContent();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                            StringBuilder sb = new StringBuilder();
                            String line = reader.readLine();
                            sb.append(line + "\n");
                            is.close();



                            String result = sb.toString();
                            JSONObject jObj = new JSONObject(result);   



                            if (jObj.getString(KEY_SUCCESS) != null) 
                            {
                                String res = jObj.getString(KEY_SUCCESS); 

                                if(Integer.parseInt(res) == 1)
                                {

                                    //Add user in db sqlite
                                    Toast.makeText(getApplicationContext(), "User ok!!!", Toast.LENGTH_SHORT).show();

                                }

                                /* Si il vaut 0, user inconnu*/
                                else
                                {

                                    AlertDialog buildexit = new AlertDialog.Builder(LoginActivity.this)
                                    .setTitle("Bad user!")
                                    .setIcon(R.drawable.ic_launcher)
                                    .setMessage("I don't know you. You want create à new account?")
                                    .setPositiveButton("Yes", new OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
                                            startActivity(i);
                                            finish();                
                                        }
                                    })
                                    .setNegativeButton("No", new OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();                
                                        }
                                    })
                                    .create();
                                    buildexit.show();
                                }
                            }
                            }else {

                                Toast.makeText(getBaseContext(),"Requiered internet connection",Toast.LENGTH_SHORT).show();
                            }
                        } 
                        catch(Exception e)
                        {
                            Log.w("W", e);
                            Toast.makeText(getBaseContext(),"error.",Toast.LENGTH_SHORT).show();
                        }

                    }else{
                        Toast.makeText(getBaseContext(),"pin incorrect.",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
        });
    }
}

查询不成功,这里是eclipse回答

09-21 07:58:02.879: W/W(8410): android.os.NetworkOnMainThreadException
09-21 07:58:02.879: W/W(8410):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-21 07:58:02.879: W/W(8410):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-21 07:58:02.879: W/W(8410):  at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
09-21 07:58:02.879: W/W(8410):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
09-21 07:58:02.879: W/W(8410):  at java.net.InetAddress.getAllByName(InetAddress.java:220)
09-21 07:58:02.879: W/W(8410):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-21 07:58:02.879: W/W(8410):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-21 07:58:02.879: W/W(8410):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)

Ps:谢谢你给我一点时间!

1 个答案:

答案 0 :(得分:0)

如果Asynctask不起作用,请尝试在onCreate方法中添加它

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);