LoginSignup
48

More than 5 years have passed since last update.

OkHttp(基本的なGET・POST)

Posted at

環境

Java:8
OkHttp:3.7.0

OkHttpとは

AndroidやJavaのアプリケーション用のHTTP/HTTP2.0のクライアント

特徴

  • 軽量である
  • レスポンスをキャッシュできる
  • Android 2.3以降であれば動作可能
  • コネクションプーリングを行い、リクエストの遅延を解消
  • ライセンスは「Apache License, Version 2.0」

インストール

Mavenの場合

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

Gradleの場合

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

前提

Java 7以上

Get

処理の流れ
1. OkHttpClientクラスのオブジェクト生成
2. RequestオブジェクトをBuilderクラスでURLなどを設定しながら生成
3. OkHttpClientクラスのcallメソッドでリクエストの送信準備
4. OkHttpClientクラスのexecuteメソッドでリクエストの送信及び、レスポンス(Responseオブジェクト)の取得
5. ResponseオブジェクトからHTMLなどが取得可能

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();

シンプルに書くと下記のように書ける

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

POST

処理の流れ
1. OkHttpClientクラスのオブジェクト生成
2. MediaTypeクラスのparseメソッドでMIMEタイプなどを事前に用意する
3. RequestBodyクラスで送信データの準備
4. RequestオブジェクトでURLと送信データなどを設定しながら生成(RequestBodyオブジェクトはpostメソッドの引数に渡す)
5.レスポンスの取得などはGETと同じ

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();

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
48