OkHttp3简单快速的上手

本文介绍了Android中使用OkHttpClient进行GET和POST异步请求的基本步骤,包括构建请求、处理响应及数据解析。在GET请求中,展示了如何获取并解析JSON数据;在POST请求中,演示了如何传递参数并根据响应处理结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注:此方法只对初学者应急使用,应该有不少基础不扎实又被推上战场的家伙。便于理解。看不懂要回去看看json数据解析,数组和集合的章节,最后随便找一下okhttp的基础教程就没问题了

get异步请求

OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("网址")
.build();

//异步请求
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {

}

@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

//数据处理
String string = response.body().string();
Log.e("输出:",":"+string);
Gson gson = new Gson();

//Gsonjx是我自己写的数据解析类,里面是网络获取的数组的里面的数据类型与名称
Gsonjx gsonjx = gson.fromJson(string, Gsonjx.class);
List<Object> rows = gsonjx.getRows();
JSONArray jsonArray = new JSONArray(rows);
for (int i = 0;i<jsonArray.length();i++){
try {
JSONObject o = (JSONObject) jsonArray.get(i);
String advImg = o.getString("advImg");

//存储数据,List<String> list = new ArrayList();


list.add("http://124.93.196.45:10001"+advImg);

} catch (JSONException e) {
e.printStackTrace();
}
}
}
});

post异步请求

//从页面上获取到的数据

String ss1 = editText1.getText().toString().trim();
String ss2 = editText2.getText().toString().trim();

OkHttpClient okHttpClient = new OkHttpClient();

//携带的参数类型
MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");

//携带参数
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username",ss1);
jsonObject.put("password",ss2);
} catch (JSONException e) {
e.printStackTrace();
}

//装进RequestBody
RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(),mediaType);
Request request = new Request.Builder()
.post(requestBody)
.url("地址")
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {

}

@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String string = response.body().string();
Log.e("输出:",":"+string);
Gson gson = new Gson();
Gsonjx gsonjx = gson.fromJson(string, Gsonjx.class);
String code = gsonjx.getCode();
if (code.equals("200")){
String token = gsonjx.getToken();

//不用管这,这是个轻量化的数据存储
SharedPreferences.Editor sharedPreferences = getSharedPreferences("wenjian",0).edit();
sharedPreferences.putString("Token",token);
sharedPreferences.commit();

Intent intent = new Intent(MainActivity.this,DbdhlActivity.class);
startActivity(intent);
}else {

}

}
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值