这几天做简单的登录注册,自己写http请求有点麻烦,于是采用okhttp3框架,OkHttp基于http协议,简化开发流程,后面还有采用retrofit+rxjava 我的学习步骤建议一步步来,先做简单的然后再优化。
【准备工作】引入OkHttp3
implementation 'com.squareup.okhttp3:okhttp:3.2.0'
联网权限申请:
<uses-permission android:name="android.permission.INTERNET"/>
简单的登录注册明码传递,其实正式是需要经过加密传输给后台,后台再加密存入数据库,后台人员并不能直接看到用户密码的。
post方法提交Json数据给后台
网上看了很多不实用的json提交都是string类型的输入,没有考虑到现实用户传参操作,都是写死了的Json,而且需要经过转义字符,不如使用JsonObject直接put进去最后toString转化为String形式json提交
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
String json=null;
try {
// network access.
//定义OkHttp
OkHttpClient loginClient=new OkHttpClient();
//定义请求体
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("password",mPassword);
jsonObject.put("telephone",mEmail);
json=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody =
RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
Request request=new Request.Builder()
.post(requestBody)
.url("http://www......")
.build();
try {
Response response=loginClient.newCall(request).execute();
if (response.code()==200){
// Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT);
System.out.println(response.code());
return true;
}else{
// Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT);
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
Intent i=new Intent(LoginActivity.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
Request.Builder设置更多的参数比如:
header
、
method
带有自我判断请求成功与否的callback
loginClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
注册实现步骤一致。
更加详细的可以看这篇文章Android中OkHttp基础用法
基本用法