Memo when HTTP communication with Java (OkHttp)

Purpose

-I want to communicate with an external API via HTTP from the process implemented in Java. ・ I want to pack XML in the body ・ I like something that is as easy to implement as possible.

Java HTTP client ... what should I use?

Refer to the article on the net, OkHttp(https://square.github.io/okhttp/) I used a library called.

<!-- http client -->
<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>3.7.0</version>
</dependency>

Implementation

In the example, XML is packed in the body and the API is called. Receives the XML String returned from the API and returns.

public String callSomething(String xml) throws IOException {
    return new OkHttpClient().newCall(
                new Request.Builder()
                    .url("[Communication URL]")
                    // basic authentication
                    .header("Authorization",
                            Credentials.basic(
                                    "[Basic authentication user]",
                                    "[Basic authentication password]"))
                    .post(RequestBody.create(MediaType.parse("text/xml"), xml))
                    .build()
            ).execute()
            .body()
            .string();
}

reference

Which Java HTTP client is better? https://qiita.com/alt_yamamoto/items/0d72276c80589493ceb4

Postscript (2019/08/13)

・ It is not good to make new each time ・ It is necessary to set the timeout time appropriately depending on the environment. I corrected it based on that point.

@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class MyService {

    private OkHttpClient client;

    @PostConstruct
    public void init() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(150, TimeUnit.SECONDS);
        builder.readTimeout(150, TimeUnit.SECONDS);
        builder.writeTimeout(150, TimeUnit.SECONDS);
        client = builder.build();
    }

    public String callSomething(String xml) throws IOException {
        try (Response res = client.newCall(
                new Request.Builder()
                    .url("[Communication URL]")
                    .header("Authorization",
                        Credentials.basic(
                            "[Basic authentication user]",
                            "[Basic authentication password]"))
                    .post(RequestBody.create(MediaType.parse("text/xml"), xml))
                .build()).execute()) {
            return res.body().string();
        }
    }
}

Recommended Posts

Memo when HTTP communication with Java (OkHttp)
[Java] JSON communication with jackson
[Note] http communication related (okhttp3)
Error when playing with java
Java study memo 2 with Progate
I tried UDP communication with Java
Try bidirectional communication with gRPC Java
Java memo
When calling API with java, javax.net.ssl.SSLHandshakeException occurs
[Java] Precautions when comparing character strings with character strings
java anything memo
Java Silver memo
HTTP / HTTPS communication
Specify ClassPath when using jupyter + Java with WSL
Java SE 7 memo
java anything memo 2
Java specification memo
Java pattern memo
[Java] Consideration when handling negative binary numbers with Integer.parseInt ()
[Java] How to get a request by HTTP communication
Notice multi thread problem when working with Java Servlet
Learning memo when learning Java for the first time (personal learning memo)
Install java with Homebrew
Java development environment memo
Change seats with java
Install Java with Ansible
java basic knowledge memo
Java learning memo (method)
Java Kuche Day memo
[Java ~ Method ~] Study memo (5)
Comfortable download with JAVA
java se 8 programmer Ⅰ memo
Java paid private memo
[OkHttp] REST-API Java SSL
Switch java with direnv
[Java ~ Array ~] Study memo 4
Java learning memo (basic)
java lambda expression memo
Java Network Basics (Communication)
(Memo) Java for statement
Download Java with Ansible
Java lambda expression [memo]
Let's scrape with Java! !!
Java learning memo (interface)
[Java] Implicit inheritance memo
Build Java with Wercker
Java learning memo (inheritance)
java competitive programming memo
[Memo] Java Linked List
Endian conversion with JAVA
Initial setting method when making Alexa Skill with JAVA (Cloud9)
Socket communication with a web browser using Java and JavaScript ②
About the behavior when doing a file map with java
Socket communication with a web browser using Java and JavaScript ①
A memo to start Java programming with VS Code (2020-04 version)
A memo when passing Ruby Silver with one official textbook