Android使用OkHttp发送POST请求
2019-08-07 本文已影响0人
i宁静的鱼
- 首先添加依赖包
implementation 'com.squareup.okhttp3:okhttp:4.0.1'
- 引入所需类
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;
- 在Activity中发送POST请求,返回json数据并解析
//登录验证
private void loginRequest() {
String username = "student";
String password = "123456";
String xdomain = "http://xuexi.iefeel.com";
boolean isLoginok = false;
String isLoginmsg = "未知错误";
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("username", username)
.add("password", password)
.build();
Request request = new Request.Builder()
.url(xdomain + "/api/login/index")
.post(requestBody)
.build();
//异步请求
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
isLoginmsg = e.getMessage();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject jsonobj = new JSONObject(response.body().string());
int rescode = jsonobj.getInt("code");
String resmsg = jsonobj.getString("msg");
if(rescode==100){
isLoginok = true;
JSONObject resdata = jsonobj.getJSONObject("data");
UserObject.userid = resdata.getInt("id");
UserObject.roleid = resdata.getInt("roleid");
UserObject.username = resdata.getString("username");
UserObject.realname = resdata.getString("realname");
}else{
isLoginmsg = resmsg;
}
}catch (JSONException e) {
isLoginmsg = e.getMessage();
}
if(isLoginok==true){
//登录成功,进入其他流程
}else{
//登录失败,提示错误 isLoginmsg
}
}
});
}
其中用到的UserObject类如下
public class UserObject {
public static int userid = 0; //用户id
public static int roleid = 0; //角色id
public static String username = ""; //用户名
public static String realname = ""; //姓名
}