okhttp中输出RequestBody的参数及参数值

Java 11-09 17:54

在一项目中使用okhttp来实现调用客户的网址,来完成推送验证。需要打印出推送的地址有参数,原使用的是直接把参数和参数值写在日志里,有多个变量名的情况下改起来比较麻烦也不好看。于是想到okhttp请求的时候,参数肯定是放在里面,直接从里面读取不更好?

方法是遍历formBody,直接输出。


// 创建OkHttpClient对象
OkHttpClient client = new OkHttpClient.Builder()
	.connectTimeout(3, TimeUnit.SECONDS)
	.writeTimeout(5, TimeUnit.SECONDS)
	.readTimeout(3, TimeUnit.SECONDS).build();
FormBody.Builder newFormBody = new FormBody.Builder();
newFormBody.add("cmd","status").add("deviceID","SM71SH2DD").add("reqTime","2021-11-02");
RequestBody requestBody = newFormBody.build();
Request request=new Request.Builder()
	.url(devCallUrl)
	.post(requestBody)
	.build();
// 把请求对象传递给Call,创建call网络请求
Call call = client.newCall(request);
call.enqueue(new Callback() { 
@Override 
public void onFailure(Call call, IOException e) {
	//call.cancel();
	StringBuffer params = new StringBuffer();
	call.cancel();
	for (int i = 0;i<newFormBody.build().size();i++){
		params.append("&")
		.append(newFormBody.build().encodedName(i))
		.append("=")
		.append(newFormBody.build().encodedValue(i));
	}
	log.info("=push error=" + devCallUrl + "?t=" + params.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
	// 未做返回判断是否推送成功  {"data": "OK"}
	//String string = response.body().string();
	StringBuffer params = new StringBuffer();
	response.close();
	for (int i = 0;i<newFormBody.build().size();i++){
		params.append("&")
		.append(newFormBody.build().encodedName(i))
		.append("=")
		.append(newFormBody.build().encodedValue(i));
	}
	log.info("=push success=" + devCallUrl + "?t=" + params.toString());
}
});

相关推荐