2011-08-03 3 views
0

이 방법에서는 아무 것도 변경하지 않았지만 갑자기 시간이 오래 걸립니다. 아래 코드 예제에서는이 오류가 발생합니다.Commons HttpClient getResponse는 매우 긴 200 초가 걸립니다.

편집 : 단일 Java 응용 프로그램에서 메서드를 추출하여 파일을로드하려고 시도했지만 동일한 시간 제한이 있습니다. 그는 3 ~ 4 시간 동안이 루프를 진행합니다. HttpMethodBase : 691 그는 내 로컬 PC에서 500 초 동안 멈추고 스레드는 잠든 상태입니다. (세션 객체 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; 
    } 
} 
+1

은 느린 서버이거나 잘못된 네트워크 연결 일 수 있습니다. 동일한 URL이 브라우저에서 또는 컬링으로 더 빨리로드됩니까? – Thilo

+0

jeah는 페이스 북의 프로필 사진을 로딩합니다. "break"는 이미지의 모든 "16 진수"데이터가 로그에 표시된 후에 표시됩니다. 내가 지금 org.apache 추적 로그를 활성화하려고 할 때 정확히 그가하고있는 곳은 휴식이다. – webstrap

+0

그리고 과거와 같은 서버와 페이스 북에 대한 다른 요청은 보통 속도입니다. – webstrap

답변

0

가 HttpClient4에 업데이트로 해결 : 여러분이 가정에서 그것을 시도 싶다면 여기 예제 코드입니다 : 다음 줄을 자고 후 outstream.close();

while ((len = instream.read(buffer)) > 0) { 
    outstream.write(buffer, 0, len); 
} 

편집이 .1 (그리고 그에 필요한 리팩토링). 그러나 누군가 위의 예에서 이유를 알고 있으면 나는 정답을 바꾼다.

관련 문제