OkHttp
2016-05-30 18:09
363 查看
Recently I want write a program to get about 10G domain in China. well, I need a good tool to help me. and that isOkHttp . OkHttp
is a third-party library developed by Square for sending and receive HTTP-based network requests.
here is my code.
from https://github.com/square/okhttp/wiki/Recipes
I'm fish, I'm on.
is a third-party library developed by Square for sending and receive HTTP-based network requests.
here is my code.
package com.yc.url; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; import com.google.gson.Gson; import okhttp3.*; public class OkHttpTest { /* * some details not mentioned here, include * (pose stream, post a file, cancel a call, Pre-call configuration, handle authentication(like ftp authentication)) * last-modify: 2016-5-30 18:02:22 * author: jack */ public static void main(String[] args) throws IOException { // SynchronousGet(); // AsynchronousGet(); // AccessingHeaders(); // PostingParams(); // ParseJson(); // CacheResponse(); Configuration(); } private static void Configuration() throws IOException{ OkHttpClient client = new OkHttpClient() .newBuilder() .connectTimeout(5, TimeUnit.SECONDS) .writeTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .build(); Request requese = new Request .Builder() .url("http://httpbin.org/delay/2") .build(); Response response = client.newCall(requese).execute(); System.out.println("Response completed : " + response); } /* * use the cache * in the cache directory, it will a journal file, it let me remember the DiskLruCache. * Console Result: Response 1 response: Response{protocol=http/1.1, code=200, message=OK, url=https://www.wikipedia.org/} Response 1 cache response: null Response 1 network response: Response{protocol=http/1.1, code=200, message=OK, url=https://www.wikipedia.org/} Response 2 response: Response{protocol=http/1.1, code=200, message=OK, url=https://www.wikipedia.org/} Response 2 cache response: Response{protocol=http/1.1, code=200, message=OK, url=https://www.wikipedia.org/} Response 2 network response: Response{protocol=http/1.1, code=304, message=Not Modified, url=https://www.wikipedia.org/} Response 2 equals Response 1? true */ private static void CacheResponse() throws IOException{ File cacheDirectory = new File("L:\\cache"); int cacheSize = 10 * 1024 * 1024; Cache cache = new Cache(cacheDirectory, cacheSize); OkHttpClient client = new OkHttpClient() .newBuilder() .cache(cache) .build(); Request request = new Request .Builder() .url("https://www.wikipedia.org/") .build(); Response response = client.newCall(request).execute(); if(!response.isSuccessful()) throw new IOException("Unexcepted code " + response); String body1 = response.body().string(); System.out.println("Response 1 response: " + response); System.out.println("Response 1 cache response: " + response.cacheResponse()); System.out.println("Response 1 network response: " + response.networkResponse()); Response again = client.newCall(request).execute(); String body2 = again.body().string(); if(!again.isSuccessful()) throw new IOException("Unexcepted code " + again); System.out.println("Response 2 response: " + again); System.out.println("Response 2 cache response: " + again.cacheResponse()); System.out.println("Response 2 network response: " + again.networkResponse()); System.out.println("Response 2 equals Response 1? " + body1.equals(body2)); } private static void ParseJson() throws IOException { OkHttpClient client = new OkHttpClient(); Gson gson = new Gson(); 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; } /** * use the wikipedia to search some word * @throws IOException */ private static void PostingParams() throws IOException { OkHttpClient client = new OkHttpClient(); RequestBody body = new FormBody.Builder().add("search", "NBA").build(); Request request = new Request.Builder().url("https://wikipedia.org/w/index.php").post(body).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } /** * Accessing Headers * * @throws IOException * */ private static void AccessingHeaders() throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://blog.csdn.net/lmj623565791/article/details/47911083") .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("Unexcepted code " + response); System.out.println("Server:" + response.header("Server")); System.out.println("Date:" + response.header("Date")); System.out.println("Vary:" + response.header("Vary")); Headers headers = response.headers(); for (int i = 0; i < headers.size(); i++) { System.out.println(headers.name(i) + ":" + headers.value(i)); } } /** * Asynchronous Get Download a file on a worker thread, and get called back * when the response is readable. The callback is made after the response * headers are ready. Reading the response body may still block. OkHttp * doesn't currently offer asynchronous APIs to receive a response body in * parts. */ private static void AsynchronousGet() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://blog.csdn.net/lmj623565791/article/details/47911083") .build(); client.newCall(request).enqueue(new Callback() { // enqueue for // asynchronous @Override public void onFailure(Call arg0, IOException arg1) { System.out.println("failure------------"); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Headers headers = response.headers(); for (int i = 0; i < headers.size(); i++) { System.out.println(headers.name(i) + ":" + headers.value(i)); } System.out.println("receivedResponseAtMillis " + response.receivedResponseAtMillis()); System.out.println("sentRequestAtMillis " + response.sentRequestAtMillis()); System.out.println("message " + response.message()); System.out.println("protocol " + response.protocol()); System.out.println("request " + response.request()); System.out.println("body " + response.body()); } } }); } /** * Synchronous Get Download a file, print its headers, and print its * response body as a string. The string() method on response body is * convenient and efficient for small documents. But if the response body is * large (greater than 1 MiB), avoid string() because it will load the * entire document into memory. In that case, prefer to process the body as * a stream. * * @throws IOException */ private static void SynchronousGet() throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); Response response = client.newCall(request).execute(); // execute = // synchronous 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()); } }
from https://github.com/square/okhttp/wiki/Recipes
I'm fish, I'm on.
相关文章推荐
- http://blog.sina.com.cn/s/blog_631a4cc40101138j.html
- iOS开发网络篇—数据缓存
- iOS开发网络篇—监测网络状态
- 网络程序设计--第一个服务器程序
- 【腾许Bugly干货分享】“HTTPS”安全在哪里?
- iOS开发网络篇—发送json数据给服务器以及多值参数
- AFNetWorking https SSL认证
- 安卓网络访问框架okhttp环境搭建
- 判断 网络状态
- 高并发服务器关键技术之线程池
- Swift - 网络请求报App Transport Security has blocked a cleartext错
- 一些关于深度学习资料和教程分享
- 强悍的 Linux —— 网络
- https ssl 加密原理
- 基于汉字字频特征实现99.99%准确率的新闻文本分类器(一)
- MFC HTTP 上传下载
- powershell windows 网络设置
- 网络请求(viewPager,Fragment,ListView)
- Java网络编程——InetAddress类和URL类
- android 基础 网络交互 HttpConnection交互