/samples/guide/src/main/java/okhttp3/recipes/SynchronousGet.java

https://gitlab.com/JoshLucid/okhttp · Java · 47 lines · 25 code · 7 blank · 15 comment · 2 complexity · de301bf548b0fe67adc82c16f7421adf MD5 · raw file

  1. /*
  2. * Copyright (C) 2014 Square, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package okhttp3.recipes;
  17. import java.io.IOException;
  18. import okhttp3.Headers;
  19. import okhttp3.OkHttpClient;
  20. import okhttp3.Request;
  21. import okhttp3.Response;
  22. public final class SynchronousGet {
  23. private final OkHttpClient client = new OkHttpClient();
  24. public void run() throws Exception {
  25. Request request = new Request.Builder()
  26. .url("https://publicobject.com/helloworld.txt")
  27. .build();
  28. try (Response response = client.newCall(request).execute()) {
  29. if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  30. Headers responseHeaders = response.headers();
  31. for (int i = 0; i < responseHeaders.size(); i++) {
  32. System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
  33. }
  34. System.out.println(response.body().string());
  35. }
  36. }
  37. public static void main(String... args) throws Exception {
  38. new SynchronousGet().run();
  39. }
  40. }