安卓中进行基于Http协议的网络访问基础总结-2

接着我的第一篇,我们来探讨一下,假如现在你需要登录用户,我们需要对用户的输入信息进行封装并验证,如果符合则令其登陆成功,否则失败。

下面我们看一下如何通过代码去实现。

这里给出两种方法去网络进行验证,同样的第一种是通过HttpClient,第二种则是通过官方推荐的HttpURLConnection进行实现。代码如下:

法一:

public static void login(final String loginname, final String password, final String code,final String sid,
final OnLoginFinishListener listener) {
new AsyncTask<Void, Void, String>(){


@Override
protected String doInBackground(Void... params) {
try {                                        
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://172.60.50.82:8080/ems/login.do");
post.setHeader("Content-Type","application/x-www-form-urlencoded");
post.setHeader("Cookie",sid);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("loginname", loginname));
parameters.add(new BasicNameValuePair("password", password));
parameters.add(new BasicNameValuePair("code", code));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
post.setEntity(entity);
HttpResponse resp = client.execute(post);
String result = EntityUtils.toString(resp.getEntity());
return result;


} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
listener.onLoginFinish(result);
};
}.execute();


}


法二:

public static void login2(final String loginname, final String password, final String code,final String sid,
final OnLoginFinishListener listener) {
new Thread(){
public void run() {
try {
URL url = new URL("http://172.60.50.82:8080/ems/login.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Cookie", sid);
connection.connect();
OutputStream out = connection.getOutputStream();
PrintWriter pw = new PrintWriter(out,true);
pw.write(getParams(loginname,password,code));
pw.close();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
final String result = br.readLine();
br.close();
new Handler(Looper.getMainLooper()).post(new Runnable() {


@Override
public void run() {
listener.onLoginFinish(result);


}
});


} catch (Exception e) {
e.printStackTrace();
}
};
}.start();


}

在登录的主函数中写如下方法:

public void login(View v){
//应该加入判空
String loginname = etName.getText().toString();
String password = etPwd.getText().toString();
String code = etCode.getText().toString();
biz.login(loginname,password,code,sid,new OnLoginFinishListener() {
@Override
public void onLoginFinish(String result) {
if(result!=null){
if(result.contains("ok")){
Intent intent = new Intent(MainActivity.this,ShowActivity.class);
startActivity(intent);
finish();
}else{
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
refresh();
etPwd.setText("");
etCode.setText("");
}
}else{
Toast.makeText(MainActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
}
}
});
}

这样的画就能实现登录的完整逻辑。需要提醒的是这两个方法中的sid是网络返回的特定的sessionid,在验证的时候需要有这个参数,而获得它的方法如下:

private void refresh() {
biz.getVertify(new OnRefreshVertifyCodeListener() {


@Override
public void onRefreshFinished(Bitmap bitmap,String sessionid) {
if(bitmap!=null)
ivVertify.setImageBitmap(bitmap);
sid = sessionid;
Log.d("TAG", "sessionid= "+sid);
}
});
}


这里的getVertify方法同样提供两种供参考,代码如下:

public static void getVertify(final OnRefreshVertifyCodeListener listener) {
new AsyncTask<Void, Void, ValueObject>(){


@Override
protected ValueObject doInBackground(Void... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://172.60.50.82:8080/ems/getCode.do");
HttpResponse resp = client.execute(get);
Header header = resp.getFirstHeader("Set-Cookie");
String value = header.getValue().split(";")[0];
HttpEntity entity = resp.getEntity();
InputStream is = entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();


ValueObject vo = new ValueObject();
vo.setBitmap(bitmap);
vo.setSessionid(value);


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




return null;
}
protected void onPostExecute(ValueObject result) {
listener.onRefreshFinished(result.getBitmap(),result.getSessionid());
};


}.execute();


}




public static void getVertify2(final OnRefreshVertifyCodeListener listener){
new Thread(){
public void run() {
try {
URL url = new URL("http://172.60.50.82:8080/ems/getCode.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();


final String value = connection.getHeaderField("Set-Cookie").split(";")[0];
InputStream is = connection.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
new Handler(Looper.getMainLooper()).post(new Runnable() {


@Override
public void run() {
listener.onRefreshFinished(bitmap,value);
}
});
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值