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!

Android Https相关完全解析 当OkHttp遇到Https

转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/48129405; 本文出自:【张鸿洋的博客】 一、概述其实这篇文章理...
  • lmj623565791
  • lmj623565791
  • 2015年09月12日 11:25
  • 1622761

关于OKHttp的Https的认证问题(全部信任)

亲测很管用,步骤如下: 1,新TrustAllcert类实现X509TrustManager接口: public class TrustAllCerts implements X509TrustMan...
  • u014800493
  • u014800493
  • 2016年10月28日 14:36
  • 5618

Android OkHttp及http、https网络请求方法

最近在搞微信支付的SDK开发,微信这个开放平台真是说不清,怎么感觉比地图和语音的SDK差的有点多,问题一大推,demo中的网络请求用的是apache的httpClient这个类来实现https请求,并...
  • seven_poul
  • seven_poul
  • 2017年04月10日 17:04
  • 3256

基于OKHttp实现对Https的支持

基于OKHttp实现对Https的支持,OKHttp版本:OKHttp3.6.0
  • u013347784
  • u013347784
  • 2017年04月14日 08:55
  • 1020

OKHTTP通信使用(三)HTTPS

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

OkHttp完全解析(五)HTTPS

OkHttp试图平衡连个相互竞争的问题:    尽可能多的主机连接: 包括运行最新版boringssl的高级主机和运行老版OpenSSL的陈旧主机。    连接的安全性: 通过证书进行远程web服...
  • OyangYujun
  • OyangYujun
  • 2015年11月25日 16:57
  • 5456

使用okhttp设置https

鸿祥的博客,连接地址http://blog.csdn.net/lmj623565791/article/details/48129405 讲的很详细,需要的可以去看看...
  • ddddwwww2
  • ddddwwww2
  • 2017年02月15日 18:54
  • 561

OkHttp关于https请求的设置

https请求由于证书验证问题,直接请求一般都会失败.一般是做证书验证处理或者忽略证书验证,这里介绍后者.解决方案从外文文章中看到,这里搬砖一下.希望对大家有帮助 public static OkH...
  • u012045061
  • u012045061
  • 2015年12月08日 14:23
  • 11568

https 证书验证 okhttp https设置

自制https证书 需要验证. okhttp不验证直接通过通过所有的https连接 代码如下 public void getONetWorkString() { OkHttp...
  • okmin3
  • okmin3
  • 2016年12月12日 18:09
  • 3173

Android使用OkHttp请求自签名的https网站

前言很多公司考虑到安全问题,项目中都采用https加密协议进行数据传输。但是一些公司又不想花一笔钱去CA申请证书,所以就采用自签名的证书。OkHttp默认是可以访问通过CA认证的HTTPS链接,例如百...
  • Alpha58
  • Alpha58
  • 2017年03月12日 19:30
  • 2544
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:OkHttp
举报原因:
原因补充:

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