OkHttp

原创 2016年05月30日 18:09:55


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!

相关文章推荐

OkHttp的深入研究 一

Okhttp是现在非常流行的网络框架,据说是可以取代我们自己手码java.net.*或Org.apache的强大工具,那么它到底有何优势呢?在其官网上有如下描述: OkHttp是一个高效的HTTP客...

OKHttp3.0的日常及入门

前言Okhttp作为现在最火的一个网络请求框架,已经有无数牛人给出了工具类等等。例如: 鸿洋大神的 Android 一个改善的okHttp封装库 和 Android OkHttp完全解析 是时候来...

okhttp使用总结

okhttp 使用总结okhttp 的使用越来越火,有必要对其进行研究。以下博客中的例子为了简单,在Eclipse中通过JAVA工程进行验证。导入OkHttpAndroidStudio添加如下代码即可...
  • lisdye2
  • lisdye2
  • 2016年06月29日 16:38
  • 4577

okhttp-3.3.1.jar

  • 2017年11月10日 11:11
  • 316KB
  • 下载

okhttp-3.2.0+okio-1.9.0工具包下载

  • 2017年10月30日 17:23
  • 380KB
  • 下载

Android平台利用OkHttp3模拟登录实现教务平台

OkHttp3模拟登录学校教务平台的流程,Cookie管理,以及遇到的几个小问题,_(:з)∠)_ 不一定试用所有教务平台但是这玩意都那么回事儿.....

okhttp-okio jar 包下载

  • 2017年11月04日 14:30
  • 448KB
  • 下载

封装好的okhttp框架 参考demo

  • 2017年10月31日 17:35
  • 1.43MB
  • 下载

使用OKHttp3 get请求 , post请求 , 多文件上传 , 包看包会

1 首先需要创建一个OKHttpClient  可以直接new一个   [java] view plain copy   OkHttpClien...

android okhttp 封装

  • 2017年10月27日 18:59
  • 60.37MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:OkHttp
举报原因:
原因补充:

(最多只允许输入30个字)