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

同步GET以下示例演示了如何同步发送GET请求,输出响应头以及将响应体转换为字符串。private final OkHttpClient client = new Client();public vo...

okHttp

创建对象 OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder().build() 请求Requests(请求) 每一个HTTP请...

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

okhttp

Android为我们提供了两种HTTP交互的方式:HttpURLConnection 和 Apache HTTP Client,虽然两者都支持HTTPS,流的上传和下载,配置超时,IPv6和连接池,已...

OkHttp

在Okhttp之前有android-async-http它的内部使用HttpClient (google在android6.0已经移除了HttpClient),还有国内的Xutils最新的额Xutil...

OKHttp通信使用(二)

以下代码摘自GitHub:https://github.com/square/okhttp/wiki/Recipes 设置缓存: OKHTTP使用时通常会先设置缓存大小: private fi...

Android okHttp 小白基本实现方法

发表于 http://blog.piasy.com,请阅读原文支持原创 http://blog.piasy.com/2016/07/11/Understand-OkHttp/1,整体思路 从使用方法...

OKHTTP通信使用(三)HTTPS

HTTPS与HTTP的区别: HTTPS和HTTP的区别主要为以下四点: 一、https协议需要到ca申请证书,一般免费证书很少,需要交费。 二、http是超文本传输协议,信息是明文传输,ht...

okHttp post&get请求

okHttp post请求 String str=”http://jingbang.com01.org:8884/client/cuser/sendCode.json”; St...

OkHttp使用介绍

OkHttp使用介绍

Android OkHttp完全解析 是时候来了解OkHttp了

Android OkHttp完全解析 是时候来了解OkHttp了
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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