View Javadoc
1   /*
2    * junixsocket
3    *
4    * Copyright 2009-2022 Christian Kohlschütter
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.newsclub.net.unix.demo.okhttp;
19  
20  import java.io.File;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.net.SocketAddress;
24  import java.time.Duration;
25  
26  import org.newsclub.net.unix.AFSocketFactory;
27  import org.newsclub.net.unix.AFUNIXSocketAddress;
28  import org.newsclub.net.unix.demo.DemoHelper;
29  import org.newsclub.net.unix.demo.nanohttpd.NanoHttpdServerDemo;
30  
31  import com.kohlschutter.util.IOUtil;
32  
33  import okhttp3.OkHttpClient;
34  import okhttp3.Request;
35  import okhttp3.Response;
36  import okhttp3.ResponseBody;
37  
38  /**
39   * Connects to {@code /tmp/junixsocket-http-server.sock} and performs an http request over that
40   * socket, using the <a href="https://square.github.io/okhttp/">OkHttp</a> HTTP client library.
41   * 
42   * If that socket is bound by {@link NanoHttpdServerDemo}, the expected output is "Hello world".
43   * 
44   * @author Christian Kohlschütter
45   * @see NanoHttpdServerDemo
46   */
47  public class OkHttpClientDemo {
48    public static void main(String[] args) throws IOException {
49      SocketAddress addr = DemoHelper.parseAddress(args, //
50          AFUNIXSocketAddress.of(new File("/tmp/junixsocket-http-server.sock")));
51  
52      OkHttpClient.Builder builder = new OkHttpClient.Builder() //
53          .socketFactory(new AFSocketFactory.FixedAddressSocketFactory(addr)) //
54          .callTimeout(Duration.ofMinutes(1));
55  
56      OkHttpClient client = builder.build();
57  
58      Request request = new Request.Builder().url("http://localhost/").build();
59      try (Response response = client.newCall(request).execute()) {
60  
61        @SuppressWarnings("resource")
62        ResponseBody body = response.body();
63        if (body != null) {
64          try (InputStream in = body.byteStream()) { // NOPMD.UseTryWithResources
65            IOUtil.transferAllBytes(in, System.out);
66          } finally {
67            body.close();
68          }
69        }
70      }
71    }
72  }