Java实现抓取百度识图结果的实现和思路-3-实现断点传输

先预告一下,源码会在这几天补全_(:зゝ∠)_

前面提及过断点传输,,若使用普通的方法去读取流的话,是一定会有错误的_(:зゝ∠)_

测试网址:


https://image.baidu.com/n/similar?queryImageUrl=http%3A%2F%2Fe.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F10dfa9ec8a1363272e2522b89b8fa0ec09fac775.jpg&querySign=2286841505,3800276236&word=&querytype=0&t=1501061892165&rn=60&sort=&fr=pc&pn=23


测试代码:

    HttpGet get=new HttpGet(你们想要测试的网址);
    InputStream is=downLoad.client.execute(get).getEntity().getContent();
    byte b[]=new byte[2048];
    String str="";
    while (is.read(b)!=-1) {
	str+=new String(b,"UTF-8");
    }
    for (String c : regExp.matcherList(str, "\"objURL\":\".+?\\\"")) {
	System.out.println(c);
    }

有图有真相

十分令人懵逼的错误_(:зゝ∠)_,若没有进行错误处理的话,一定会在处理错误的方面花费大量时间......得不偿失_(:зゝ∠)_


如何判断是否有断点传输?

万能的F12

响应头中的Accept-Encoding中就声明了gzip,这是一个类似于压缩包的东西,因为不知道要加载多少数量的图片,所以将他们压缩起来减少服务器内存压力是一种常见的做法_(:зゝ∠)_




不推荐在请求头中设置Accept-Encoding,因为没有多少效果,_(:зゝ∠)_,而且说不定还不给你数据了

好了,开始上源码

package EII;

import java.io.IOException;

import java.io.InputStream;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class downLoad {
	public static CloseableHttpClient client=HttpClients.createDefault();
	public static String download(String url) throws ClientProtocolException, IOException{
		HttpGet get=new HttpGet(url);
		InputStream is=client.execute(get).getEntity().getContent();
		String text="";
		while (true) {
			int r=is.read();
			int length=is.available()+1;
			if(r==-1)
				break;
			if(length==0)
				continue;
			byte[] b=new byte[length];
			b[0]=(byte) r;
			is.read(b, 1, length-1);
			text+=new String(b);
		}
		is.close();
		return text;
	}
	public static String download(InputStream is) throws IOException{
		String text="";
		while (true) {
			int r=is.read();
			int length=is.available()+1;
			if(r==-1)
				break;
			if(length==0)
				continue;
			byte[] b=new byte[length];
			b[0]=(byte) r;
			is.read(b, 1, length-1);
			text+=new String(b,"UTF-8");
		}
		is.close();
		return text;
	}
}
原理是InputStream读取一个字符串之后得到当前长度,因为断点传输并不是将全部的数据马上放进去,而是一次放部分数据进去,

只要读取到的数据并不是-1的话,available是会返回长度的,或许画个图更清晰

因为read会读取一个字符,所以循环读取并不是从0开始,而是从1开始到结束


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值