1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.newsclub.net.unix.demo.okhttp;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InterruptedIOException;
23 import java.net.NoRouteToHostException;
24 import java.net.SocketAddress;
25 import java.util.concurrent.TimeUnit;
26
27 import org.newsclub.net.unix.AFSocketFactory;
28 import org.newsclub.net.unix.AFTIPCSocketAddress;
29 import org.newsclub.net.unix.demo.DemoHelper;
30 import org.newsclub.net.unix.demo.nanohttpd.NanoHttpdServerDemo;
31
32 import com.kohlschutter.util.IOUtil;
33
34 import okhttp3.OkHttpClient;
35 import okhttp3.Request;
36 import okhttp3.Response;
37 import okhttp3.ResponseBody;
38
39
40
41
42
43
44
45
46
47
48
49 @SuppressWarnings("CatchAndPrintStackTrace" )
50 public class OkHttpClientTIPCDemo {
51 public static void main(String[] args) throws IOException, InterruptedException {
52
53 SocketAddress addr = DemoHelper.parseAddress(args,
54 AFTIPCSocketAddress.ofService(8080, 1));
55
56 OkHttpClient client = new OkHttpClient.Builder()
57 .socketFactory(new AFSocketFactory.FixedAddressSocketFactory(addr))
58
59 .retryOnConnectionFailure(true)
60 .connectTimeout(500, TimeUnit.MILLISECONDS)
61 .readTimeout(500, TimeUnit.MILLISECONDS)
62 .callTimeout(500, TimeUnit.MILLISECONDS)
63 .build();
64
65
66
67 while (!Thread.interrupted()) {
68 Request request = new Request.Builder().url("http://localhost/").build();
69 try (Response response = client.newCall(request).execute()) {
70
71
72
73
74
75 @SuppressWarnings("resource")
76 ResponseBody body = response.body();
77 if (body != null) {
78 try (InputStream in = body.byteStream()) {
79 IOUtil.transferAllBytes(in, System.out);
80 } finally {
81 body.close();
82 }
83 }
84 } catch (InterruptedIOException | NoRouteToHostException e) {
85 e.printStackTrace();
86 }
87
88
89 client.connectionPool().evictAll();
90
91
92 Thread.sleep(100);
93 }
94 }
95 }