Androidネットフレームワーク学習のOKHttp
OKHTTP
ok Http:
OKHttpはAndroid版Httpクライアントです。非常に効率的で、SPDY、接続池、GZIP、HTTPキャッシュに対応しています。デフォルトでは、OKHttpは二次接続、SSLの握手問題のように、よくあるネット問題を自動的に処理します。
もしあなたのアプリケーションにOKHttpが統合されたら、RetrofitはデフォルトでOKHttpを使って他のネットワーク層の要求を処理します。
。
An HTTP&SPDY client for Android and Java appration s
Android 4.4からHttpURLConnectionの底辺実現にはok Http.
使用要求:Androidに対して:2.3以上、Javaに対して:java 7以上
二つのモジュール:
Khttp-urlconnection実装.HttpURLConnection API;
okhttp-apacheはApache HttpClient APIを実現します。
依存:
オカオhttps://github.com/square/okio) Okio、which OkHttp uses for fast I/O and rezable buffers.
インストール:
maven:
同期GET:
一つのワークスレッドでファイルをダウンロードし、応答が読み取り可能な場合はCallbackインターフェースをリピートする。応答を読み出すと現在のスレッドがブロックされます。OkHttpは、現段階では、非同期アプリを提供せずに応答体を受信する。
Posting a String:
キャッシュ応答のためには、読み書きができるキャッシュディレクトリとキャッシュサイズの制限が必要です。このキャッシュディレクトリはプライベートであるべきです。信頼されていないプログラムはキャッシュ内容を読み取ることができません。
キャッシュディレクトリの一つが複数のキャッシュアクセスを同時に持つのはエラーです。ほとんどのプログラムは一度だけnew OkHttp()を呼び出す必要があります。最初の呼び出しでキャッシュを設定し、他のところではこのインスタンスを呼び出すだけでいいです。2つのバッファ例が干渉し、応答キャッシュを破壊し、プログラムが崩壊する恐れがあります。
応答キャッシュは、設定としてHTTPヘッダを使用する。リクエストにCache-Coontrol:max-stale=3600を追加できます。OkHttpキャッシュはサポートされます。あなたのサービスは、応答ヘッダを介して、応答キャッシュのどれぐらいの時間を決定しますか?例えば、Cache-Coontrol:max-age=9600を使用します。
ok Http:
OKHttpはAndroid版Httpクライアントです。非常に効率的で、SPDY、接続池、GZIP、HTTPキャッシュに対応しています。デフォルトでは、OKHttpは二次接続、SSLの握手問題のように、よくあるネット問題を自動的に処理します。
もしあなたのアプリケーションにOKHttpが統合されたら、RetrofitはデフォルトでOKHttpを使って他のネットワーク層の要求を処理します。
。
An HTTP&SPDY client for Android and Java appration s
Android 4.4からHttpURLConnectionの底辺実現にはok Http.
使用要求:Androidに対して:2.3以上、Javaに対して:java 7以上
二つのモジュール:
Khttp-urlconnection実装.HttpURLConnection API;
okhttp-apacheはApache HttpClient APIを実現します。
依存:
オカオhttps://github.com/square/okio) Okio、which OkHttp uses for fast I/O and rezable buffers.
インストール:
maven:
<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>2.3.0</version>
</dependency>
Grade:compile 'com.squareup.okhttp:okhttp:2.3.0'
GET A URL同期GET:
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
非同期GET:一つのワークスレッドでファイルをダウンロードし、応答が読み取り可能な場合はCallbackインターフェースをリピートする。応答を読み出すと現在のスレッドがブロックされます。OkHttpは、現段階では、非同期アプリを提供せずに応答体を受信する。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Request request, Throwable throwable) {
throwable.printStackTrace();
}
@Override public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
});
}
ヘッドへのアクセス: private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://api.github.com/repos/square/okhttp/issues")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.addHeader("Accept", "application/vnd.github.v3+json")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println("Server: " + response.header("Server"));
System.out.println("Date: " + response.header("Date"));
System.out.println("Vary: " + response.headers("Vary"));
}
POST TO A SERVERPosting a String:
public static final MediaType jsonReq
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(jsonReq, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
Posting Streaming: public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody requestBody = new RequestBody() {
@Override public MediaType contentType() {
return MEDIA_TYPE_MARKDOWN;
}
@Override public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("Numbers
");
sink.writeUtf8("-------
");
for (int i = 2; i <= 997; i++) {
sink.writeUtf8(String.format(" * %s = %s
", i, factor(i)));
}
}
private String factor(int n) {
for (int i = 2; i < n; i++) {
int x = n / i;
if (x * i == n) return factor(x) + " × " + i;
}
return Integer.toString(n);
}
};
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
Posting a File: public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
File file = new File("README.md");
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
Posting from parameters:private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody formBody = new FormEncodingBuilder()
.add("search", "Jurassic Park")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
Posting a multiipad request: private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"image\""),
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
Posing Json with Gson private final OkHttpClient client = new OkHttpClient();
private final Gson gson = new Gson();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://api.github.com/gists/c2a7c39532239ff261be")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue().content);
}
}
static class Gist {
Map<String, GistFile> files;
}
static class GistFile {
String content;
}
Resonse Caching:キャッシュ応答のためには、読み書きができるキャッシュディレクトリとキャッシュサイズの制限が必要です。このキャッシュディレクトリはプライベートであるべきです。信頼されていないプログラムはキャッシュ内容を読み取ることができません。
キャッシュディレクトリの一つが複数のキャッシュアクセスを同時に持つのはエラーです。ほとんどのプログラムは一度だけnew OkHttp()を呼び出す必要があります。最初の呼び出しでキャッシュを設定し、他のところではこのインスタンスを呼び出すだけでいいです。2つのバッファ例が干渉し、応答キャッシュを破壊し、プログラムが崩壊する恐れがあります。
応答キャッシュは、設定としてHTTPヘッダを使用する。リクエストにCache-Coontrol:max-stale=3600を追加できます。OkHttpキャッシュはサポートされます。あなたのサービスは、応答ヘッダを介して、応答キャッシュのどれぐらいの時間を決定しますか?例えば、Cache-Coontrol:max-age=9600を使用します。
private final OkHttpClient client;
public CacheResponse(File cacheDirectory) throws Exception {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(cacheDirectory, cacheSize);
client = new OkHttpClient();
client.setCache(cache);
}
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Response response1 = client.newCall(request).execute();
if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);
String response1Body = response1.body().string();
System.out.println("Response 1 response: " + response1);
System.out.println("Response 1 cache response: " + response1.cacheResponse());
System.out.println("Response 1 network response: " + response1.networkResponse());
}
Call Call final Call call = client.newCall(request);
call.cancel();
Timeouts:private final OkHttpClient client;
public ConfigureTimeouts() throws Exception {
client = new OkHttpClient();
client.setConnectTimeout(10, TimeUnit.SECONDS);
client.setWriteTimeout(10, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
}
Handling Authentication:private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
client.setAuthenticator(new Authenticator() {
@Override public Request authenticate(Proxy proxy, Response response) {
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic("jesse", "password1");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
@Override public Request authenticateProxy(Proxy proxy, Response response) {
return null; // Null indicates no attempt to authenticate.
}
});
Request request = new Request.Builder()
.url("http://publicobject.com/secrets/hellosecret.txt")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
は、検証に失敗した時に何度も再試行することを避けるために、nullに戻ることによって検証を放棄することができます。 if (responseCount(response) >= 3) {
return null; // If we've failed 3 times, give up.
}
//
private int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}
Interceptorsclass LoggingInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
logger.info(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
logger.info(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
Apple Interceptors:OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LoggingInterceptor());
Network InterceptorsOkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new LoggingInterceptor());