Commons HttpClient getResponse takes very long 200 seconds
I changed nothing in this method but suddenly it takes very long. The code example below produces this error.
EDIT: i extracted the method in a single java application and tried to load the file and i have the same timeout. The 3 or 4. time he goes through this loop HttpMethodBase:691 he stops for 500 seconds at my local pc and the thread is sleeping. After sleeping the next line is outstream.close();
while ((len = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
EDIT: Here is the example code if you wanna try it at home :) (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() {
// ignore开发者_如何学Cs 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;
}
}
Fixed it with an update to HttpClient4.1 (and some refactoring required therefor). But if someone knows the reason in the example above i switch the correct answer.
精彩评论