OKHTTP官网
使用OKHTTP3主要包括以下几个步骤:
1.在清单文件AndroidManifest.xml中添加网络权限
2.在app的build.gradle下添加依赖
implementation(“com.squareup.okhttp3:okhttp:4.10.0”)
3.参考该文章:https://blog.csdn.net/m0_37796683/article/details/101029208
private OkHttpClient client;
client = new OkHttpClient();
//Post异步请求
public void postAsync(PayOrder payOrder){
FormBody formBody=new FormBody.Builder().add("payType",payOrder.payType)
.add("days",payOrder.days)
.add("amount",payOrder.amount)
.add("equipmentCode",payOrder.equipmentCode)
.add("accountType",payOrder.accountType)
.add("orderNo",payOrder.orderNo)
.build();
Request request=new Request.Builder().url("http://***.***.***.***/地址路径/recharge").post(formBody).build();
Call call= client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.d(TAG, "postAsync onFailure: 请求失败"+e.toString());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
String responseData = response.body().string();
DataRecharge data = new DataRecharge();
try {
JSONObject jsonObject = new JSONObject(responseData);
data.setCode(jsonObject.getString("code"));
data.setMsg(jsonObject.getString("msg"));
data.setData(jsonObject.getString("data"));
if(data.getCode().equals("200")){
QR_Code = stringToBitmap(data.getMsg());
showResponse();
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "postAsync onResponse: 请求成功 " + responseData);
}
});
}
//Get异步请求
public void getAsync(String orderNo){
Log.d(TAG, "getAsync orderNo: "+orderNo);
Request request=new Request.Builder().url("http://152.***.***.***/equip-api/api/outside/getOrderStatus?orderNo="+orderNo).get().build();
Call call=client.newCall(request);
//异步请求要调用回调 自带子线程
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.d(TAG, "getAsync onFailure: 请求失败");
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
String responseData = response.body().string();
Log.d(TAG, "getAsync onResponse: 请求成功"+responseData);
try {
JSONObject jsonObject = new JSONObject(responseData);
String code = jsonObject.getString("code");
if(code.equals("200")){
payStatus = jsonObject.getString("msg");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}