[JAVA] OkHttp (basic GET / POST)

environment

Java:8 OkHttp:3.7.0

What is OkHttp

HTTP / HTTP 2.0 client for Android and Java applications

Feature

Installation

For Maven

.xml


<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>3.7.0</version>
</dependency>

For Gradle

.gradle


compile 'com.squareup.okhttp3:okhttp:3.7.0'

Premise

Java 7 and above

Get Process flow

  1. Object creation of OkHttpClient class
  2. Generate Request object while setting URL etc. in Builder class
  3. Prepare to send the request with the call method of the OkHttpClient class
  4. Send request and get response (Response object) by execute method of OkHttpClient class
  5. HTML etc. can be obtained from Response object

.java


String url = "http://www.casareal.co.jp";
OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
Response response = call.execute();
ResponseBody body = response.body();

If you write it simply, you can write it as follows

.java


Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
response.body().string();

POST Process flow

  1. Object creation of OkHttpClient class
  2. Prepare the MIME type etc. in advance with the parse method of the MediaType class
  3. Preparation of transmission data with RequestBody class
  4. Generate while setting URL and transmission data etc. in Request object (RequestBody object is passed to the argument of post method)
  5. Getting the response is the same as GET

.java


OkHttpClient client = new OkHttpClient();
MediaType MIMEType= MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create (MIMEType,"{}");
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = client.newCall(request).execute();

reference

http://square.github.io/okhttp/

Recommended Posts

OkHttp (basic GET / POST)
[Ruby] Difference between get and post
Get the result of POST in Java