android okhttp json,Android使用OkHttp发送POST请求

1.首先添加依赖包implementation 'com.squareup.okhttp3:okhttp:4.0.1'

2.引入所需类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;

3.在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 = ""; //姓名

}

没有了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值