我在这种方法中没有改变任何东西,但突然它需要很长时间。下面的代码示例会产生此错误。
编辑:我在单个 java 应用程序中提取了该方法并尝试加载文件并且我有相同的超时。他通过这个循环 HttpMethodBase:691 的 3 或 4 时间,他在我的本地电脑上停止了 500 秒,并且线程正在休眠。睡觉后下一行是outstream.close();
while ((len = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
编辑:如果您想在家尝试,这是示例代码:) (httpClient 3.1)
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
public class TestLoadImage {
/**
* @param args
*/
public static void main(String[] args) {
byte[] image = loadPhotoFromUrl("https://fbcdn-sphotos-a.akamaihd.net/photos-ak-snc1/v2635/232/115/68310606562/n68310606562_2255479_948765.jpg");
System.out.println(image.length);
}
private static class GetMethodIgnoringContentLength extends GetMethod {
public GetMethodIgnoringContentLength(String uri) {
super(uri);
}
@Override
public long getResponseContentLength() {
// ignores content-length header, fakes "not specified":
return -1;
}
}
public static byte[] loadPhotoFromUrl(String photoUrl) {
HttpClient httpClient = new HttpClient();
httpClient.getParams().setBooleanParameter("http.connection.stalecheck", true);
GetMethod get = new GetMethodIgnoringContentLength(photoUrl);
try {
int httpStatus = httpClient.executeMethod(get);
if (httpStatus == HttpStatus.SC_OK) {
byte[] imageBytes = get.getResponseBody();
if (imageBytes.length > 0) {
return imageBytes;
} else {
System.out.println("Failed: empty response/zero data");
}
} else {
System.out.println("Failed: "+ httpStatus);
}
} catch (IOException ioe) {
System.out.println( ioe);
} finally {
get.releaseConnection();
}
return null;
}
}