2013-11-21 6 views
0

문자열의 웹 사이트 응답을 반환하는 자바 메소드가 있습니다. 이제이 요청의 진행 상황을 추적 할 수있는 가능성을 추가하고 싶습니다. 내가 (contenLength/readBytes) * 100 통해 계산할 수 있습니다. 하지만이 정보를 올바르게 검색하고 변경 될 때마다 진행 상황을 업데이트하는 방법을 모르겠습니다. 현재 방법은 다음과 같습니다.Java에서 HTTPRequest 진행하기

public String executePost(URL url) { 
    StringBuffer sb = new StringBuffer(); 
      int readBytes = 0; 
      int contentLength = 0; 
      int progress = 0; 
    try { 
     String newString = url.toString().replace(" ", "%20"); 
     URL newURL = new URL(newString); 
     URLConnection conn = newURL.openConnection(); 
     conn.setDoOutput(true); 
        contentLength = conn.contentLength(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(
       conn.getInputStream())); 
     String line; 
     while ((line = rd.readLine()) != null) { 
      sb.append(line); 
          readBytes += line.getBytes("ISO-8859-2").length + 2; 
          progress = (readBytes/contentLength)*100; 
          System.out.println(progress); 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return sb.toString(); 
} 
+0

component.setCursor(new Cursor(Cursor.WAIT_CURSOR)); 

를 통해 대기 커서를 표시하여 그것을 해결하고 -은'println' 작품을 그 목적을 위해, 아니? 콜백 메소드를'executePost()'에 전달할 수 있습니까? 답변에 대한 –

답변

1

진행률을 추적하는 InputStream을 만들 수 있습니다.

public class CountingInputStream extends FilterInputStream { 
    long count; 

    protected CountingInputStream(InputStream in) 
    { 
    super(in); 
    } 
    public long getCount() 
    { 
    return count; 
    } 
    @Override 
    public int read() throws IOException 
    { 
    final int read = super.read(); 
    if(read>=0) count++; 
    return read; 
    } 
    @Override 
    public int read(byte[] b, int off, int len) throws IOException { 
    final int read = super.read(b, off, len); 
    if(read>0) count+=read; 
    return read; 
    } 
    @Override 
    public long skip(long n) throws IOException { 
    final long skipped = super.skip(n); 
    if(skipped>0) count+=skipped; 
    return skipped; 
    } 
} 

는 그런 다음 이전 진행할 수

CountingInputStream counting = new CountingInputStream(conn.getInputStream()); 
BufferedReader rd = new BufferedReader(new InputStreamReader(counting)); 

에 선

BufferedReader rd = new BufferedReader(new InputStreamReader(
      conn.getInputStream())); 

을 변경하고 counting.getCount()를 통해 acual 수를 쿼리합니다.

정수 계산을 사용할 때 진행률이 항상 전체 계수와 같거나 적으므로 정밀도 손실이 너무 크지 않도록해야합니다. 따라서 progressInPercent=progressInBytes*100/totalNumberOfBytes을 사용해야합니다.

스윙을 사용할 때 유사한 기능을 제공하는 클래스 ProgressMonitor 및이 이미 있습니다.

+0

흠 감사합니다,하지만 난 당신이 여기에 설명 내가 (while 루프에서) 진행을 위해 다음과 같은 출력을 얻을 일을 할 때 -821800.0 -821800.0 -821800.0 -5605600.0 -5605600.0 -5605600.0 -5605600.0 을 -1144000.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 01,235 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 16,100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 – dehlen

+0

총 수와 처리 된 바이트 수에 대한 개별 값을 인쇄 할 수 있습니까?일부 'URL'/ HTTP 서버의 경우 헤더에 길이가 제공되지 않습니다. 이 경우 값을 설명 할 수있는'-1'이 반환됩니다 (끝에 '100'제외). 연결에서 총 금액을 미리 알려주지 않으면 특정 URL에 대한 백분율을 제공 할 수 없습니다. – Holger

+0

내 contentLength가 이번에 -1이므로 음수가 인쇄된다고 생각합니다. 그러나 어떻게하면 단계별로 단계적으로 진행할 수 있습니까? 편집 : 나는 하나씩 가치를 인쇄 하고이 게시물을 업데이 트됩니다. 잠깐만. – dehlen

1

감사합니다. 어쨌든. 난 그냥 당신이 "검색 ... 및 업데이트"는 무엇을 의미하는 정교한 수 다시

component.setCursor(Cursor.getDefaultCursor());