1.先导入依赖implementation ‘com.squareup.okhttp3:okhttp:3.10.0’
2.get请求
private void get() {
String url = "填入接口路径";
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.get()//默认就是GET请求,可以不写
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "onResponse: " + response.body().string());
}
});
}
3.post请求
private void post() {
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("money", money)//参数1
.add("qrCode", qrCode)//参数2
.build();
Request request = new Request.Builder()
.url("填入接口路径")
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "onResponse: ");
JSONObject jsonObj;
try {
String str = response.body().string();
//返回的字符串转成json格式
jsonObj = new JSONObject(str);
String code = jsonObj.getString("code");
String message = jsonObj.getString("message");
String data = jsonObj.getString("data");
Log.d(TAG, "onResponse: code---" + code + ", message---" + message + ", data---" + data);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "onResponse: e-----------" + e.toString());
}
}
});
}