Java 使用HttpClient验证用户名和密码

Java 使用HttpClient验证用户名和密码,java,php,android,android-asynctask,indexoutofboundsexception,Java,Php,Android,Android Asynctask,Indexoutofboundsexception,我试图向一个php文件发送一个POST请求,然后该文件返回一条json消息,用于用户名和密码验证。使用我的代码,我得到一个错误ArrayIndexOutOfBoundsException:length=0;此行上的索引=0: HttpGet get=new HttpGet(strings[0]); 在我的代码中,当单击login按钮时,它调用asyncTask类,然后运行应用程序。它崩溃之前,我甚至可以测试代码,但我不知道为什么。我是HttpClient的新手,所以请温柔一点。 这是我在asy

我试图向一个php文件发送一个POST请求,然后该文件返回一条json消息,用于用户名和密码验证。使用我的代码,我得到一个错误ArrayIndexOutOfBoundsException:length=0;此行上的索引=0:

HttpGet get=new HttpGet(strings[0]);
在我的代码中,当单击login按钮时,它调用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;
    }
}
公共类下载文件任务扩展异步任务{
私有字符串名称,pwd;
私人物流活动物流活动;
布尔bloggedIn;
公共下载文件任务(LoginActivity LoginActivity、字符串名称、字符串pwd){
this.loginActivity=loginActivity;
this.name=name;
这个.pwd=pwd;
}
@凌驾
受保护的空位背景(空位…空位){
HttpClient HttpClient=新的DefaultHttpClient();
HttpGet=新的HttpGet();
试一试{
URI网站=新的URI(“login.php”);
get.setURI(网站);
}捕获(URISyntaxException e){
e、 printStackTrace();
}
HttpPost-HttpPost=newhttppost(“login.php”);
List nameValuePairs=新的ArrayList(2);
字符串结果=null;
添加(新的BasicNameValuePair(“name”,name));
添加(新的BasicNameValuePair(“密码”,pwd));
试一试{
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
}捕获(不支持的编码异常e){
e、 printStackTrace();
}
HttpResponse response=null;//错误
试一试{
response=httpClient.execute(httpPost);
}捕获(IOE异常){
e、 printStackTrace();
}
HttpEntity=response.getEntity();
InputStream instream=null;
试一试{
instream=entity.getContent();
}捕获(IOE异常){
e、 printStackTrace();
}
结果=转换流到管柱(流内);
试一试{
流内关闭();
}捕获(IOE异常){
e、 printStackTrace();
}
if(Utility.isNotNull(名称)和&Utility.isNotNull(pwd)){
RequestParams params=新的RequestParams();
if(实用程序验证(名称,pwd)){
参数put(“用户名”,名称);
参数put(“密码”,pwd);
bloggedIn=true;
onPostExecute();
}否则{
loginActivity.InvalidToast();
}
}否则{
loginActivity.EmptyToast();
}
返回null;
}
私有字符串convertStreamToString(InputStream instream){
BufferedReader reader=新的BufferedReader(新的InputStreamReader(instream));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
流内关闭();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}
受保护的void onPostExecute(){
如果(bloggedIn=true){
loginActivity.navigatetoMainActivity();
}否则{
loginActivity.InvalidToast();
}
}
私有静态类实用程序{
静态模式;
静态匹配器;
静态模式1;
静态匹配器匹配器1;
静态字符串名称\u PATTERN=“ABCDEF”;
静态字符串PWD_PATTERN=“ghijkl”;
公共静态布尔验证(字符串名称、字符串pwd){
pattern=pattern.compile(NAME\u pattern);
pattern1=Pattern.compile(PWD_模式);
matcher=pattern.matcher(名称);
匹配器1=模式1.匹配器(pwd);
返回matcher.matches()&&matcher1.matches();
}
公共静态布尔值isNotNull(字符串名称){
返回名称!=null&&name.trim().length()>0?true:false;
}
}

}

更好地使用这种方式,我给出了两种从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;

}
}
package com.example.testdemo;
导入org.apache.http.Header;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.StringEntity;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.util.EntityUtils;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.provider.Settings.Global;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入com.loopj.android.http.AsyncHttpClient;
导入com.loopj.android.http.JsonHttpResponseHandler;
导入com.loopj.android.http.RequestParams;
公共类MainActivity扩展了活动{
AsyncHttpClient=新的AsyncHttpClient();
RequestParams params=新的RequestParams();
字符串响应;
public static String URL=“http://”这里是您的服务器URL其他明智的locatl路径集“/服务/服务/登录”;
字符串[]数据字段,数据值;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//GetLogin();
数据字段=新字符串[]{“用户名”,“密码”};
datavalue=newstring[]{“hardik”,“Parmar”};//这里设置您的edittext值
新建getServices().execute();
}
私有类getServices扩展异步任务{
private ProgressDialog=新建ProgressDialog(MainActivity.this);
受保护的void onPreExecute(){
setMessage(“请稍候…”);
Dialog.show();
}
@凌驾
受保护的Void doInBackground(字符串…参数){
//TODO自动生成的方法存根
试一试{
resp=postData(URL、数据字段、数据值);
Log.e(“注册”,“响应:+resp”);
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(void resu