duanhuang4306 2015-11-09 21:15
浏览 576

使用HttpClient验证用户名和密码

I am trying to send a POST request to a php file which then sends back a json message for username and password authentication. with my code I get an error ArrayIndexOutOfBoundsException: length=0; index=0 on this line:

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

In my code, when the login button is clicked, it calls an asyncTask class which then runs the application. it crashes before I can even test the code but I am not sure why. I am new to HttpClient so please be gentle. This is my snippet of code in the asynctask class

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 + "
");
        }
    } 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条回答 默认 最新

  • duanchan5458 2015-11-10 04:10
    关注

    better to use on this way i given two way to get response from web services.

    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 this is a library for the getting response form server. GetLogin() method is using AsyncHttpClient. i always use this method.

    and in your side may be mistake is

    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示