我正在Java程序中切换到OkHttp,下面是相关代码
这是一个多线程应用程序
public class MyApplication implements Runnable {
public static Integer numberOfThreads = 0;
public static Boolean useProxy = true;
@Override
public void run() {
try {
ThreadLocalManager.okHttp.set(new OkHttp());
String results = ThreadLocalManager.okHttp.get().test();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class OkHttp {
volatile OkHttpClient okHttpClient;
public OkHttp() {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888));
okHttpClient = new OkHttpClient.Builder().proxy(null).connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS).writeTimeout(5, TimeUnit.SECONDS).build();
}
public String test() throws IOException {
String result = null;
RequestBody body = RequestBody.create(null, "test");
Request request = new Request.Builder().url("https://google.com").post(body).addHeader(":scheme", "https")
.addHeader("content-type", "application/x-www-form-urlencoded").addHeader("user-agent", "okhttp/3.8.1")
.build();
Response response = okHttpClient.newCall(request).execute();
result = response.body().string();
response.body().close();
return result;
}
}
当我运行上述程序时,在控制台中确实看到了“完成”,但是该程序继续运行。这仅在我调用test()
类的OkHttp
方法时发生。知道为什么程序没有结束吗?