/** *//**
* author by http://www.bt285.cn http://www.5a520.cn
*/
package instream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public final class HttpReader {
public static final int MAX_RETRY = 10;
private static long content_length;
private URL url;
private HttpURLConnection httpConnection;
private InputStream in_stream;
private long cur_pos; //用于决定seek方法中是否执行文件定位
private int connect_timeout;
private int read_timeout;
public HttpReader(URL u) {
this(u, 5000, 5000);
}
public HttpReader(URL u, int connect_timeout, int read_timeout) {
this.connect_timeout = connect_timeout;
this.read_timeout = read_timeout;
url = u;
if (content_length == 0) {
int retry = 0;
while (retry < HttpReader.MAX_RETRY)
try {
this.seek(0);
content_length = httpConnection.getContentLength();
break;
} catch (Exception e) {
retry++;
}
}
}
public static long getContentLength() {
return content_length;
}
public int read(byte[] b, int off, int len) throws IOException {
int r = in_stream.read(b, off, len);
cur_pos += r;
return r;
}
public int getData(byte[] b, int off, int len) throws IOException {
int r, rema = len;
while (rema > 0) {
if ((r = in_stream.read(b, off, rema)) == -1) {
return -1;
}
rema -= r;
off += r;
cur_pos += r;
}
return len;
}
public void close() {
if (httpConnection != null) {
httpConnection.disconnect();
httpConnection = null;
}
if (in_stream != null) {
try {
in_stream.close();
} catch (IOException e) {}
in_stream = null;
}
url = null;
}
/**//*
* 抛出异常通知再试
* 响应码503可能是由某种暂时的原因引起的,例如同一IP频繁的连接请求可能遭服务器拒绝
*/
public void seek(long start_pos) throws IOException {
if (start_pos == cur_pos && in_stream != null)
return;
if (httpConnection != null) {
httpConnection.disconnect();
httpConnection = null;
}
if (in_stream != null) {
in_stream.close();
in_stream = null;
}
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setConnectTimeout(connect_timeout);
httpConnection.setReadTimeout(read_timeout);
String sProperty = "bytes=" + start_pos + "-";
httpConnection.setRequestProperty("Range", sProperty);
//httpConnection.setRequestProperty("Connection", "Keep-Alive");
int responseCode = httpConnection.getResponseCode();
if (responseCode < 200 || responseCode >= 300) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
throw new IOException("HTTP responseCode="+responseCode);
}
in_stream = httpConnection.getInputStream();
cur_pos = start_pos;
}
}
|