Help us understand the problem. What is going on with this article?

OkHttp調べてみた

More than 1 year has passed since last update.

Http ClientのOkHttpの簡単な使い方です
http://square.github.io/okhttp/
JavaのライブラリなのでAndroidでなくても使えます。
今回はAndroidで使うことを想定してます。
バージョンは2.5.0です。

gradle

compile 'com.squareup.okhttp:okhttp:2.5.0'

クライアント作成

OkHttpClient client = new OkHttpClient();

GET

get requestを作る

Request request = new Request.Builder()
           .url(url)
           .build();

GET リクエスト(同期)

Response response = client.newCall(request).execute();

同期実行はexecute()を使います。Androidアプリだとメインスレッド上で実行されるので通信中はアプリが固まります。

GET リクエスト(非同期)

client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
            }

            @Override
            public void onResponse(Response response) throws IOException {
            }
        });

非同期実行はenqueue(Callback)を使って結果をCallbackメソッドで受け取る。

Callbackの中でUIを操作すると落ちる

client.newCall(request).enqueue(new Callback() {
final Handler mainHandler = new Handler(Looper.getMainLooper());
            @Override
            public void onFailure(final Request request, final IOException e) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        //UI操作
                    }
                });
            }

            @Override
            public void onResponse(final Response response) throws IOException {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        //UI操作
                    }
                });
             }
        });
}

new Handler(Looper.getMainLooper())を使ってUIスレッドで操作する。

データ取得

final String content = response.body().string();

POST

Stringやファイルなど簡単にできるようです。
OkHttpレシピに色々あります。下記はファイルのPOSTです。

MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");
File file = new File("README.md");

Request request = new Request.Builder()
    .url("url")
    .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
    .build();
Response response = client.newCall(request).execute();

Header設定

Request request = new Request.Builder()
        .url("https://api.github.com/repos/square/okhttp/issues")
        .header("User-Agent", "UA:hoge")
        .addHeader("Accept", "hoge")
        .build();

Header情報はrequestに設定します。

Cookieを使う

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);

上記の設定でCookieが使えるようになりますが、アプリを再起動するとCookieが消えるので、再起動しても同じCookieを使うためにSharedPreferencesなどでCookieを保存する必要があります。自分でcookieManagerを継承してputとなどで保存してもいいのですが
franmontielさんの

PersistentCookieStore.java
SerializableHttpCookie.java

を使わせてもらうと良さそうです。
franmontiel/PersistentCookieStore.java

CookieManager cookieManager = new CookieManager(new PersistentCookieStore(Application.getContext()), CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);

参考

https://github.com/square/okhttp/wiki/Recipes
http://qiita.com/ryugoo/items/478ba23cda0f57bd21e8
http://qiita.com/oqrusk/items/1b3091de877c38eac0de
https://gist.github.com/franmontiel/ed12a2295566b7076161

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away