我使用以下代码使用okhttp客户端发出异步请求:
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.*;
import java.util.concurrent.TimeUnit ;
import groovy.json.JsonOutput;
import java.util.concurrent.CompletableFuture ;
import java.io.IOException;
class CallbackFuture extends CompletableFuture<Response> implements Callback {
String name;
public void setName(String name)
{
this.name=name
}
public void onResponse(Call call, Response response) {
print('dpone'+name)
super.complete(response);
}
public void onFailure(Call call, IOException e){
super.completeExceptionally(e);
}
}
MediaType MEDIA_TYPE_PNG = MediaType.parse("multipart/form-data");
OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(900, TimeUnit.SECONDS).readTimeout(900, TimeUnit.SECONDS)
.writeTimeout(900, TimeUnit.SECONDS)
.build();
OkHttpClient client1 = new OkHttpClient().newBuilder().connectTimeout(900, TimeUnit.SECONDS).readTimeout(900, TimeUnit.SECONDS)
.writeTimeout(900, TimeUnit.SECONDS)
.build();
OkHttpClient client2 = new OkHttpClient().newBuilder().connectTimeout(900, TimeUnit.SECONDS).readTimeout(900, TimeUnit.SECONDS)
.writeTimeout(900, TimeUnit.SECONDS)
.build();
//MediaType mediaType = MediaType.parse("multipart/form-data");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("request","test.yaml",
RequestBody.create(MEDIA_TYPE_PNG,
new File("/home/test/test.yaml")))
.build();
Request request = new Request.Builder()
.url("https://gateway/deployment")
.method("POST", body)
.addHeader("Content-Type", "multipart/form-data")
.addHeader("Authorization", "test")
.build();
CallbackFuture future = new CallbackFuture();
future.setName('x')
client.newCall(request).enqueue(future);
println(' sent 1')
CallbackFuture future2 = new CallbackFuture();
future2.setName('y')
client1.newCall(request).enqueue(future2);
println(' sent 2')
CallbackFuture future3 = new CallbackFuture();
future3.setName('z')
client2.newCall(request).enqueue(future3);
println(' sent 3')
Response response = future.get();
Response response1 = future2.get();
Response response2 = future3.get();
print(response)
print(response1)
print(response2)
我正在测试的onresponse中有一个虚拟打印日志,但它没有被打印出来。
输出:
已发送1已发送2已发送3响应{协议=http/1.1,代码=202,消息=,url=https://gateway/deployment}响应{协议=http/1.1,代码=202,消息=已接受,
网址=https://gateway/deployment}响应{协议=http/1.1,代码=202,消息=已接受,url=https://gateway/deployment}
网址=https://gateway/deployment}响应{协议=http/1.1,代码=202,消息=已接受,url=https://gateway/deployment}我错过了什么?
这是用groovy编写的,我假设onresponse在收到响应后被调用?
暂无答案!
目前还没有任何答案,快来回答吧!