本次学习了网络请求的应用,列出的实例主要是实现输入手机号,点击登录按钮后,向服务器发送请求,从而获取用户的user_id。服务器接收和返回的数据是json格式的,为了更方便一点,此处还需要使用到Gson来进行解析。需要想服务器发送的Body的字段如下(此处只使用手机号):
下面开始本次实例。
1、AS导入与请求网络权限配置
(1)在libs下添加这三个jar包
(2)在AndroidManifest文件中打开联网的权限:
<uses-permission android:name="android.permission.INTERNET"/>
2、登录页面的布局文件activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/bg">
<ImageView
android:id="@+id/login_iv_pp"
android:layout_width="92dp"
android:layout_height="105dp"
android:src="@mipmap/pp_1"
android:layout_gravity="center_horizontal"
android:layout_marginTop="75dp"/>
<LinearLayout
android:id="@+id/login_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="27dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/login_im_phone"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@mipmap/phone"
android:layout_marginLeft="63dp"
android:layout_gravity="center_vertical"/>
<EditText
android:id="@+id/login_et_phone"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:background="#0000"
android:hint="@string/phone_hint"
android:textColorHint="@color/line_below"
android:layout_gravity="center_vertical"
android:layout_marginLeft="6dp"
android:textSize="13dp"
android:textColor="@color/btn_text"
android:inputType="phone"
android:maxLength="11"/>
</LinearLayout>
<View
android:id="@+id/login_phone_bloweline"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/line_below"
android:layout_marginTop="8dp"
android:layout_marginLeft="55dp"
android:layout_marginRight="55dp"/>
<LinearLayout
android:id="@+id/login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/login_im_password"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@mipmap/lock"
android:layout_marginLeft="63dp"
android:layout_gravity="center_vertical"/>
<EditText
android:id="@+id/login_et_password"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:background="#0000"
android:layout_marginLeft="6dp"
android:hint="@string/password_hint"
android:textColorHint="@color/line_below"
android:layout_gravity="center_vertical"
android:textSize="13dp"
android:textColor="@color/btn_text"
android:inputType="textPassword"
android:maxLength="20"/>
<ImageView
android:id="@+id/login_eye"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@mipmap/eye2"
android:layout_marginRight="57dp"/>
</LinearLayout>
<View
android:id="@+id/login_password_bloweline"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/line_below"
android:layout_marginTop="8dp"
android:layout_marginLeft="55dp"
android:layout_marginRight="55dp"/>
<Button
android:id="@+id/login_btn_login"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="55dp"
android:layout_marginRight="55dp"
android:layout_marginTop="46dp"
android:layout_gravity="center_horizontal"
android:background="@drawable/btn_login"
android:text="登录"
android:textSize="16dp"
android:textColor="#000000"/>
<Button
android:id="@+id/login_btn_register"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="55dp"
android:layout_marginRight="55dp"
android:layout_marginTop="20dp"
android:layout_gravity="center_horizontal"
android:background="@drawable/btn_register"
android:text="注册"
android:textSize="16dp"
android:textColor="@color/btn_text"/>
<TextView
android:id="@+id/login_tv_forget_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="@string/wangjimima"
android:textSize="13dp"
android:textColor="@color/btn_text"/>
</LinearLayout>
3、UserIdRequest.java
public class UserIdRequest {
String client_id;
int req_time;
String sign_key;
String mob_phone;
String card_id;
public UserIdRequest(String client_id, int req_time, String sign_key, String mob_phone, String card_id) {
this.client_id = client_id;
this.req_time = req_time;
this.sign_key = sign_key;
this.mob_phone = mob_phone;
this.card_id = card_id;
}
public String getClient_id() {
return client_id;
}
public void setClient_id(String client_id) {
this.client_id = client_id;
}
public int getReq_time() {
return req_time;
}
public void setReq_time(int req_time) {
this.req_time = req_time;
}
public String getSign_key() {
return sign_key;
}
public void setSign_key(String sign_key) {
this.sign_key = sign_key;
}
public String getMob_phone() {
return mob_phone;
}
public void setMob_phone(String mob_phone) {
this.mob_phone = mob_phone;
}
public String getCard_id() {
return card_id;
}
public void setCard_id(String card_id) {
this.card_id = card_id;
}
@Override
public String toString() {
return "UserIdRequest{" +
"client_id='" + client_id + '\'' +
", req_time=" + req_time +
", sign_key='" + sign_key + '\'' +
", mob_phone='" + mob_phone + '\'' +
", card_id='" + card_id + '\'' +
'}';
}
}
public class UserIdResponse extends BaseResponse{ Body body; public UserIdResponse(int code, String code_msg, Body body) { super(code, code_msg); this.body = body; } public Body getBody() { return body; } public void setBody(Body body) { this.body = body; } public class Body{ int user_id; public Body(int user_id) { this.user_id = user_id; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } @Override public String toString() { return "Body{" + "user_id=" + user_id + '}'; } } }
5、BaseResponse.java
6、LoginActivity.java中代码编写public class BaseResponse { int code; String code_msg; public BaseResponse(int code,String code_msg){ this.code = code; this.code_msg = code_msg; } public int getCode(){ return code; } public void setCode(int code){ this.code = code; } public String getCode_msg(){ return code_msg; } public void setCode_msg(String code_msg){ this.code_msg = code_msg; } public String toString(){ return "BaseResponse{" + "code='" + code + '\'' + "code_msg='" + code_msg + '\'' + "}"; } }
public class LoginActivity extends Activity {
private static final int MSG_GET_USER_ID_SUCCEED = 0X13;
private static final int MSG_GET_USER_ID_FAILED = 0X14;
public EditText editText;
EditText etPhone,etPassword;
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case MSG_GET_USER_ID_SUCCEED:
int userID = msg.arg1;
Log.e("TAG", "userID = "+userID);//获取user_id成功,则打印
login(userID);
break;
case MSG_GET_USER_ID_FAILED:
String msgObj = (String)msg.obj;
//获取user_id失败,直接弹框显示返回的code_msg内容
Toast.makeText(LoginActivity.this, msgObj, Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etPhone = (EditText)findViewById(R.id.login_et_phone);
etPassword = (EditText)findViewById(R.id.login_et_password);
Button btnLogin = (Button)findViewById(R.id.login_btn_login);
//登录
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getUserID();
}
});
//因为android不允许主线程上的网络调用,所以只能在单独的线程或后台服务上进行调用,此处单独建了一个线程
private void getUserID(){
final Thread mUserId = new Thread(){
@Override
public void run(){
String client_id = "xxxx";//此处为固定值,根据各自的平台情况填写
int req_time = (int)(System.currentTimeMillis()/1000);
String sign_key = Md5Util.md5(req_time + "binwen");//因计算时需要用md5,所以还需写一个Md5Util的工具类
String mob_phone = etPhone.getText().toString();//根据手机号编辑框数据的手机号获取手机号字符串
String card_id = "";
UserIdRequest mUserIdRequest = new UserIdRequest(client_id,req_time,sign_key,mob_phone,card_id);
Gson mGson = new Gson();
String json = mGson.toJson(mUserIdRequest);//将请求的数据转换为json格式
Log.e("TAG", json);
String url = "XXXXXX";//引号中填写请求地址
//OkHttp
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//实例化一个OkHttpClient并创建一个Request对象,OkHttpClient可以看作发送者,可以看作请求者Request
OkHttpClient mOkHttpClient = new OkHttpClient();
Request mRequest = new Request.Builder()
.url(url)
.post(RequestBody.create(JSON, json))
.build();
//请求过后的响应,获取返回的json字符串
Response mUserIdResponse = null;
try {
mUserIdResponse = mOkHttpClient.newCall(mRequest).execute();
} catch (IOException e) {
e.printStackTrace();
}
String mUserIdResult = null;
try {
mUserIdResult = mUserIdResponse.body().string();
Log.e("TAG", "mResponse.body().string() = \n" + mUserIdResult);
} catch (IOException e) {
e.printStackTrace();
}
//将响应得到的json字符串用Gson解析。为了防止出现crash,此处先判断BaseResponse返回的code为0还是1,为0,则再接收UserIdResponse的数据,为1,则直接发送消息处理
BaseResponse mBaseResponse = mGson.fromJson(mUserIdResult, BaseResponse.class);
int code1 = mBaseResponse.getCode();
String codeMsg1= mBaseResponse.getCode_msg();
if(code1 == 0){
UserIdResponse mUserIdResponseString = mGson.fromJson(mUserIdResult,UserIdResponse.class);
int userID = mUserIdResponseString.getBody().getUser_id();
Log.e("TAG", "code_msg = " + codeMsg1);
Log.e("TAG", "code = " + code1);
Log.e("TAG", "user_id = " + userID);
Message msg = new Message();
msg.what = MSG_GET_USER_ID_SUCCEED;
msg.arg1 = userID;
mHandler.sendMessage(msg);
}else {
Message msg = new Message();
msg.what = MSG_GET_USER_ID_FAILED;
msg.obj = codeMsg1;
mHandler.sendMessage(msg);
}
}
};
mUserId.start();
}