OkHttp


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.

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.

阅读更多
版权声明:have a nice day! https://blog.csdn.net/cjvs9k/article/details/51540011
个人分类: android deeper
上一篇window server2012 + IIS8.0 + tomcat 集成环境搭建
下一篇对开发的一些思考
想对作者说点什么? 我来说一句

okhttp

2016年10月29日 393KB 下载

没有更多推荐了,返回首页

关闭
关闭