使用HttpClient验证用户名和密码

时间:2015-11-09 21:15:12

标签: java php android android-asynctask indexoutofboundsexception

我正在尝试向php文件发送POST请求,然后发送回用于用户名和密码身份验证的json消息。用我的代码我得到一个错误ArrayIndexOutOfBoundsException:length = 0;此行上的index = 0:

HttpGet get=new HttpGet(strings[0]);

在我的代码中,当单击登录按钮时,它会调用asyncTask类,然后运行该应用程序。它在我甚至可以测试代码之前崩溃但我不确定为什么。我是HttpClient的新手,所以请保持温柔。 这是我在asynctask类中的代码片段

public class DownloadFilesTask extends AsyncTask<Void, Void, Void> {

private String name, pwd;
private LoginActivity loginActivity;
boolean bloggedIn;

public DownloadFilesTask(LoginActivity loginActivity,String name, String pwd){
    this.loginActivity=loginActivity;
    this.name=name;
    this.pwd=pwd;
}


@Override
protected Void doInBackground(Void... voids) {
    HttpClient httpClient=new DefaultHttpClient();
    HttpGet get=new HttpGet();
    try {
        URI website=new URI("login.php");
        get.setURI(website);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    HttpPost httpPost=new HttpPost("login.php");
    List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2);
    String result=null;
    nameValuePairs.add(new BasicNameValuePair("name", name));
    nameValuePairs.add(new BasicNameValuePair("password", pwd));
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    HttpResponse response = null; //error
    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        e.printStackTrace();
    }

    HttpEntity entity=response.getEntity();
    InputStream instream= null;
    try {
        instream = entity.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }
    result=convertStreamToString(instream);
    try {
        instream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }



    if (Utility.isNotNull(name) && Utility.isNotNull(pwd)) {
        RequestParams params = new RequestParams();
        if (Utility.validate(name, pwd)) {
            params.put("username", name);
            params.put("password", pwd);
            bloggedIn=true;
            onPostExecute();
        } else {
            loginActivity.InvalidToast();
        }
    } else {
        loginActivity.EmptyToast();
    }
    return null;
}

private String convertStreamToString(InputStream instream) {
    BufferedReader reader=new BufferedReader(new InputStreamReader(instream));
    StringBuilder sb=new StringBuilder();
    String line=null;
    try {
        while ((line=reader.readLine())!=null){
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            instream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

protected void onPostExecute(){
    if (bloggedIn=true) {
        loginActivity.navigatetoMainActivity();
    }else{
        loginActivity.InvalidToast();
    }
}


private static class Utility {
    static Pattern pattern;
    static Matcher matcher;
    static Pattern pattern1;
    static Matcher matcher1;
    static String NAME_PATTERN="ABCDEF";
    static String PWD_PATTERN="ghijkl";

    public static boolean validate(String name,String pwd){
        pattern=Pattern.compile(NAME_PATTERN);
        pattern1=Pattern.compile(PWD_PATTERN);
        matcher=pattern.matcher(name);
        matcher1=pattern1.matcher(pwd);
        return matcher.matches()&& matcher1.matches();
    }

    public static boolean isNotNull(String name) {
        return name!=null && name.trim().length()>0 ? true: false;
    }
}

}

1 个答案:

答案 0 :(得分:0)

更好地以这种方式使用我给出了两种从Web服务获得响应的方法。

package com.example.testdemo;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class MainActivity extends Activity {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String resp;
public static String URL = "http://"here your server url other wise locatl     path set"/service/service/login";
String[] datafield, datavalue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // GetLogin();
    datafield = new String[] { "username", "password" };
    datavalue = new String[] { "hardik", "Parmar" }; // here set your edittext value
    new getServices().execute();

}

private class getServices extends AsyncTask<String, Void, Void> {
    private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

    protected void onPreExecute() {

        Dialog.setMessage("Please Wait...");
        Dialog.show();
    }

    @Override
    protected Void doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {
            resp = postData(URL, datafield, datavalue);
            Log.e("SignUp", "Response : " + resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Dialog.dismiss();
        try {
            JSONObject jsonObj = new JSONObject(resp);
            Log.e("get the JSON RESPONCES ", ": :: : : :: : : " + jsonObj);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private void GetLogin() {
    // TODO Auto-generated method stub
    params.put("username", "hardik");
    params.put("password", "Parmar");

    client.post(URL, params,
            new JsonHttpResponseHandler() {
                @Override
                public void onStart() {
                    // TODO Auto-generated method stub
                    super.onStart();
                    Log.e("Services ", "On start");
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                        Throwable throwable, JSONArray errorResponse) {
                    // TODO Auto-generated method stub
                    super.onFailure(statusCode, headers, throwable,
                            errorResponse);
                    Log.e("Services ", "On failure  Array " + errorResponse);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers,
                        JSONObject response) {
                    // TODO Auto-generated method stub
                    super.onSuccess(statusCode, headers, response);
                    Log.e("Services ", "On Sucess " + response);
                }

                @Override
                public void onFinish() {
                    // TODO Auto-generated method stub
                    super.onFinish();
                    Log.e("Services ", "On finish");
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                        Throwable throwable, JSONObject errorResponse) {
                    // TODO Auto-generated method stub
                    super.onFailure(statusCode, headers, throwable,
                            errorResponse);
                    Log.e("Services ", "On faulure Json Object "
                            + errorResponse);
                }
            });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, 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);
}

public static String postData(String mUrl, String[] datafield,
        String[] datavalue) {
    // TODO Auto-generated method stub
    String respStr = null;
    try {

        JSONObject json = new JSONObject();
        if (datafield != null) {
            for (int i = 0; i < datavalue.length; i++) {
                json.put(datafield[i], datavalue[i]);
            }
        }

        Log.e("json", "" + json);

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(mUrl);
        post.setHeader("content-type", "application/json; charset=UTF-8");

        StringEntity entity = new StringEntity(json.toString());
        post.setEntity(entity);

        HttpResponse resp = httpClient.execute(post);
        respStr = EntityUtils.toString(resp.getEntity());
    } catch (Throwable t) {
    }

    return respStr;

}
}

AsyncHttpClient这是获取响应表单服务器的库。 GetLogin()方法正在使用AsyncHttpClient。我总是使用这种方法。

并且在你身边可能是错误的