2011-01-15 2 views
3

POST 메서드 (apache의 httpclient)를 사용하여 웹 사이트에 로그온합니다. HttpClient가 HttpPost를 실행하게하고, 연결 관리자가 그것을 풀어 준 다음, pdf를 다운로드하기 위해 php-URL 파일을 여는 GET 메시지를 게시하고 싶습니다. 하지만 얻을 모두는의 HTML 파일 "세션 만료"페이지 (에 println : File: index_GT_neu.html?fehlermeldung=fehler_sessioncheck)입니다Java httpclient가 웹 사이트에 로그인하여 파일을 다운로드합니다 - 세션 문제!

내가 사이트에 로그온 할 HttpClient를 인스턴스를 사용하면, 내가 열 수있을 것이라고 생각했다 로그온 후에 만 ​​사용할 수있는 또 다른 URL입니다. 그러나 명백하게 나는 틀렸다. 누군가 나에게 힌트를 줄 수 있습니까? 미리 감사드립니다.

// prepare post method 
    HttpPost post = new HttpPost("http://epaper02.niedersachsen.com/epaper/index_GT_neu.html"); 

    //prepare get method 
    HttpGet httpget = new HttpGet("http://epaper01.niedersachsen.com/epaper/getfile.php?pdf=0114_GTB_HP_01.pdf&zeitung=GT&ekZeitung=&Y=11&M=01&D=14&C=0"); 

    // add parameters to the post method 
    List <NameValuePair> parameters = new ArrayList <NameValuePair>(); 
    parameters.add(new BasicNameValuePair("username", "test")); 
    parameters.add(new BasicNameValuePair("passwort", "test")); 
    UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8); 
    post.setEntity(sendentity); 

    // create the client and execute the post method 
    HttpClient client = new DefaultHttpClient(); 
    HttpResponse postResponse = client.execute(post); 

    //Output the Response from the POST 
    System.out.print(convertInputStreamToString(postResponse.getEntity().getContent())); 

    //releasing POST 
    EntityUtils.consume(postResponse.getEntity()); 

    //Execute get 
    HttpContext context = new BasicHttpContext(); 
    HttpResponse getResponse = client.execute(httpget, context); 
    System.out.println("Statusline: " + getResponse.getStatusLine()); 

    if (getResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) 
     throw new IOException(getResponse.getStatusLine().toString()); 
    HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); 
    String currentUrl = URLDecoder.decode(currentReq.getURI().toString(), "UTF-8"); 

    int i = currentUrl.lastIndexOf('/'); 
    String fileName = null; 
    if (i < 0) { 
     fileName = currentUrl; 
    } else { 
     fileName = currentUrl.substring(i + 1); 
    } 
    System.out.println("File: " + fileName); 

    //Create file 
    OutputStream os = new FileOutputStream(fileName); 
    InputStream is = getResponse.getEntity().getContent(); 
    byte[] buf = new byte[4096]; 
    int read; 
    while ((read = is.read(buf)) != -1) { 
     os.write(buf, 0, read); 
    } 
    os.close(); 

    client.getConnectionManager().shutdown(); 
+1

와이어 로깅을 사용하도록 설정하고 (http://hc.apache.org/httpcomponents-client-ga/logging.html#Wire_Logging) POST로받은 쿠키와 동일한 쿠키를 GET으로 보내고 있는지 확인하십시오. – fglez

+0

서버 로깅 사용자는 어떻게됩니까? 세션, 쿠키? – Harry

답변

0

나는이 라이브러리에 익숙하지 오전하지만 게시물을 호출하기 전에 컨텍스트를 만드는 시도하고 GET에 대해 동일한 맥락 재사용 :

HttpContext context = new BasicHttpContext(); 
    // create the client and execute the post method 
    HttpClient client = new DefaultHttpClient(); 
    HttpResponse postResponse = client.execute(post,context); 
    ... 

    HttpResponse getResponse = client.execute(httpget, context); 
+0

아니요, 작동하지 않습니다. 하지만 어쨌든 덕분에, 당신의 도움을 주셔서 감사합니다! – tzippy

+0

좋아,이 예제를 보았다 : http : //stackoverflow.com/questions/678630/how-do-i-make-an-http-request-using-cookies-on-android. HttpClient에는 세션 정보가 있어야하며 게시물을 사용한 후에 세션 쿠키가 포함되어 있는지 확인하십시오. 또한 게시물의 응답에서 System.out을 주석 처리하십시오. 한 번만 소모 할 수있는 입력 스트림을 소비 할 수 있습니다. 여기서는 완전히 추측 할 수 있습니다. – jny

+0

그 두 가지를 시도했습니다. POST 후에 쿠키가 생성됩니다. 하지만 여전히 sessioncheck 오류가 발생합니다. 어쩌면 내가 PHP getfile URL되는 전화하려고 URL을 함께 할 수있다? 그러나 이것이 세션 오류로 이어지지 않도록해야합니까? – tzippy

1

이 내 주요 외모가 같은 것입니다 기본적으로 DefaultHttpClient에는 쿠키 저장소가 없습니다. 처음에 채워지거나 HTTP 클라이언트와 상호 작용하는 동안 획득되는 쿠키를 저장하려면 쿠키 저장소가 필요합니다. 이 주제를 파헤 치자 마자 쿠키의 범위/공유에 대해 생각하기 시작합니다. 아직 조금 늦게 HTH를

내가 아는
DefaultHttpClient client = new DefaultHttpClient(); 
client.setCookieStore(new BasicCookieStore()); 

, 이것은 수 있습니다을 :

당신은 하나 개의 코드 추가 라인과 쿠키의 저장을 활성화 할 수 있습니다.