如何快速读取网页返回数据
java吧
全部回复
仅看楼主
level 8
gameloftyou 楼主
有时返回数据的长度是不能正确获得的吧,于是我用了下面这样的代码,可是速度跟直接预先设置一个足够大的字节数组来直接读取慢太多了!!!,有什么好方法没有?
InputStream is = s.getInputStream();
byte bdata[] = new byte[512];
int pos = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((pos=is.read(bdata, 0, 512))!=-1){
baos.write(bdata,0,pos);
}
bdata = null;
bdata = baos.toByteArray();
2012年06月05日 13点06分 1
吧务
level 15
/** * 读网页源代码 *
* @param url * 网页地址
* @param data *POST数据 (留空则GET)
* @param charset *编码类型
* @return 网页源代码 */
public static String POST(String url, String data, String charset) {
String method = data == null || data.equals("") ? "GET" : "POST";
// 如果data数据为空,则执行GET请求,否则为POST
StringBuffer sb = new StringBuffer();
try {URL u = new URL(url);
HttpURLConnection urlcon = (HttpURLConnection) u.openConnection();
urlcon.setDoOutput(true);
urlcon.setDoInput(true);
// urlcon.setRequestProperty("User-Agent",// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
// urlcon.setRequestProperty("Accept",// "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
// urlcon.setRequestProperty("Referer", url);
// urlcon.setRequestProperty("Accept-Language", "zh-cn");
// urlcon.setRequestProperty("Content-Type",// "application/x-www-form-urlencoded");
// urlcon.setRequestProperty("Content-Length", data.length()+"");
urlcon.setUseCaches(false);
urlcon.setRequestMethod(method);
urlcon.setReadTimeout(5000);
urlcon.setConnectTimeout(5000);
if (method.equals("POST")) { // POST请求时发送数据
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(urlcon.getOutputStream(), charset));
bw.write(data);
bw.flush();
bw.close();
}
// 读返回的HTML源代码
BufferedReader br = new BufferedReader(new InputStreamReader(urlcon.getInputStream(), charset));
String t;
while ((t = br.readLine()) != null) {
sb.append(t + "\n");}br.close();
} catch (Exception e) {e.printStackTrace();}
return sb.toString();}
2012年06月05日 13点06分 2
level 8
gameloftyou 楼主
我用的是Socket,
我把读取部分换成你这种的
BufferedReader br = new BufferedReader(new InputStreamReader( urlcon.getInputStream(), charset));
String t;
while ((t = br.readLine()) != null) {
sb.append(t + "\n"); } br.close();
} catch (Exception e) { e.printStackTrace(); }
return sb.toString(); }
速度好像也不是很理想啊
比如我测试一贴吧页面,未压缩的,大小大概有60多k,就要花费半分多钟
2012年06月05日 13点06分 3
level 8
gameloftyou 楼主
估计大的页面也要像浏览器那样,先下载gzip格式的,然后再在本地解压。
2012年06月05日 13点06分 4
吧务
level 15
我擦,我直接读很快啊。而且速度基本忽略不计
2012年06月05日 13点06分 5
吧务
level 15
我测试了很久,访问百度,每次都是 150 毫秒以下
2012年06月05日 13点06分 6
level 8
gameloftyou 楼主
嗯,你这个确实秒解,不知道为什么我用Socket速度却很慢[揉脸]
2012年06月05日 14点06分 7
吧务
level 15
socket我只会简单的Socket s=new Socket("地址",端口)
[Love]
2012年06月05日 14点06分 8
1