6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AndroidでHTTP通信(OkHttp)

Posted at

AndroidでHTTP通信するためにOkHttpを使ってみました。

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

やりたい事

  • HTTP GET
  • 取得するデータは小さいものを想定しています。

注意した点

  • メインスレッドから呼ばれる事を考慮して、コールバックを使用した非同期処理としました。

サンプルコード

HttpClient.java
package com.ykao.sample.httpclient;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpClient implements Callback {
    public void getWithUrlString(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(this);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        System.out.println("onFailure");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        System.out.println("Status code: " + response.code());
        System.out.println("Body: " + response.body().string().substring(0, 19) + "...");
    }

}
build.gradle
    ...
dependencies {
    ...
    // add
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
}
AndroidManifest.xml
    ...
    <!-- add -->
    <uses-permission android:name="android.permission.INTERNET" />
    ...
6
10
0

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
6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?