okhttp

Android为我们提供了两种HTTP交互的方式:HttpURLConnection 和 Apache HTTP Client,虽然两者都支持HTTPS,流的上传和下载,配置超时,IPv6和连接池,已足够满足我们各种HTTP请求的需求。但更高效的HTTP请求可以让您的应用运行更快、更节省流量。而OkHttp库就是为此而生,并且google已不推荐使用HTTP Client,而原生的HttpURLConnection使用太繁琐。

OKhttp优点:

1 如果服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP
2 使用 OkHttp 无需重写程序中的网络代码,OkHttp实现了几乎和java.net.HttpURLConnection一样的API。
3 支持异步请求 案例一:发送get请求

package com.qf.day28;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 使用OkHttp实现get请求
 * @author wgy
 *
 */
public class OkHttpDemo1 {
	public static void main(String[] args) throws Exception {
		//1创建OkHttpClient对象
		OkHttpClient client=new OkHttpClient();
		//2创建请求
		Request request=new Request.Builder()
						.url("http://10.0.161.117:8080/Day27Web/MyServlet")
						.build();

		//3创建响应对象
		Response response=client.newCall(request).execute();
		//4处理响应
		if(response.code()==200){
			System.out.println(response.body().string());
		}
	}
}	

案例二:发送post请求

package com.qf.day28;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

/**
 * 使用OkHttp实现Post请求
 * @author wgy
 *
 */
public class OkHttpDemo2 {
	public static void main(String[] args) throws Exception {
		//1创建OkHttpClient对象
		OkHttpClient client=new OkHttpClient();
		//2创建表单体(默认编码是utf-8)
		FormBody body=new FormBody.Builder()
					.add("username", "张三2")
					.add("pwd", "123456")
					.build();
		//3创建请求对象
		Request request=new Request.Builder()
						.url("http://10.0.161.117:8080/Day27Web/LoginServlet")
						.post(body)
						.build();
		//4创建响应对象
		Response response=client.newCall(request).execute();
		if(response.code()==200){
			System.out.println(response.body().string());
		}
		
	}
}

案例三:下载文件

package com.qf.day28;

import java.io.FileOutputStream;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 使用OkHttp实现文件下载
 * 
 * @author wgy
 * 
 */
public class OkHttpDemo3 {
	public static void main(String[] args) throws Exception{
		// 1创建OkHttpClient
		OkHttpClient client = new OkHttpClient();
		// 2创建请求对象
		Request request = new Request.Builder()
				.url("http://10.0.161.117:8080/Day27Web/2.jpg")
				.build();
		//3创建响应对象
		Response response=client.newCall(request)
							.execute();
		//4处理响应
		if(response.code()==200){
			//获取流对象
			InputStream is=response.body().byteStream();
			FileOutputStream fos=new FileOutputStream("d:\\haha.jpg");
			byte[] buf=new  byte[1024];
			int len=0;
			while((len=is.read(buf))!=-1){
				fos.write(buf, 0, len);
			}
			is.close();
			fos.close();
			System.out.println("下载完毕");
				
		}
	}
}

案例四:使用多线程下载文件

package com.qf.Task3;

import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpDownload {
	public static void main(String[] args) throws Exception{
		String urlString = "http://localhost:8080/Day27Web/java.pdf";
		String filePath = "d:\\java.pdf";
		OkHttpClient client = new OkHttpClient();
		Request request = new Request.Builder()
							.url(urlString)
							.build();
		Response response = client.newCall(request).execute();
		
		if (response.code()==200) {
			long length =response.body().contentLength();
			//System.out.println(length);
			int sublen = (int) (length%4==0?length/4:length/4+1);
			int lastlen = (int) (length-sublen);
			
			downloadThread d1 = new downloadThread(0*sublen,sublen,urlString,filePath);
			downloadThread d2 = new downloadThread(1*sublen,sublen,urlString,filePath);
			downloadThread d3 = new downloadThread(2*sublen,sublen,urlString,filePath);
			downloadThread d4 = new downloadThread(3*sublen,lastlen,urlString,filePath);
			d1.start();
			d2.start();
			d3.start();
			d4.start();
		}
	}
}

class downloadThread extends Thread {
	private int skipCount;//跳过字节数
	private int length;//下载长度
	private String urlString;//服务器地址
	private String filePath;//所存放的路径
	
	public downloadThread(int skipCount,int lentgth,String urlString,String filePath) {
		// TODO Auto-generated constructor stub
		this.skipCount = skipCount;
		this.length = lentgth;
		this.urlString = urlString;
		this.filePath = filePath;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		try {
			
			OkHttpClient client = new OkHttpClient();
			Request request = new Request.Builder()
								.url(urlString)
								.addHeader("Range", "bytes="+skipCount+"-"+(skipCount+length-1))
								.build();
			Response response = client.newCall(request).execute();
			//System.out.println(response.code());
			if (response.code()==206) {
				System.out.println(Thread.currentThread().getName()+"开始下载");
				InputStream is =response.body().byteStream();
				RandomAccessFile raf = new RandomAccessFile(filePath,"rw");
				raf.seek(skipCount);
				byte[] buf = new byte[1024*4];
				int len =0;
				while((len = is.read(buf))!=-1){
					raf.write(buf,0,len);
				}
				is.close();
				raf.close();
				System.out.println(Thread.currentThread().getName()+"下载完成");
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值