java - 使用HttpClient验证用户名和密码

标签 java php android android-asynctask indexoutofboundsexception

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

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

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

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;
    }
}

}

最佳答案

更好地使用这种方式,我给出了两种从网络服务获取响应的方法。

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。我一直用这个方法。

而在你这边可能会犯的错误是

关于java - 使用HttpClient验证用户名和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33618407/

相关文章:

java - Glassfish 3.1.1 启动失败

java - 如何使 int 在随机生成时不被使用两次?

php - Laravel phpunit 总是 404

android - 如何在 Android 上对 RxJava Completable.error 进行单元测试

java - 无法使用 ArrayList<HashMap<String,?>>> 填充 listView

android - 在 Android 2.2 中获取单个位置更新

java - 同一 Controller Spring MVC 中的多个用户

java - 是否可以在 64 位 Ubuntu 上安装 java 1.4?

php - 如何在 Symfony 3 中正确存储日期时间?

php - 是否可以在 php 中动态定义类属性?