문제

서버에 게시 한 후 리디렉션을 잡는 방법을 알아내는 데 도움이 필요합니다. 먼저 서버에서 쿠키를 얻기 위해해야합니다. 그런 다음 쿠키 및 추가 매개 변수로 게시물을 수행합니다. 그런 다음 서버는 302 리디렉션으로 답변합니다. 해당 리디렉션의 URL을 어떻게 얻습니까?

코드는 다음과 같습니다.

HttpGet get = new HttpGet(urlOne);

try {
    //Creating a local instance of cookie store.
    CookieStore cookieJar = new BasicCookieStore();

    // Creating a local HTTP context
    HttpContext localContext = new BasicHttpContext();

    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar);

    HttpResponse response = httpClient.execute(get, localContext);
    HttpEntity entity = response.getEntity();

    System.out.println("------------------GET----------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
    }

    // Print out cookies obtained from server
    List<Cookie> cookies = cookieJar.getCookies();
    for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Local cookie: " + cookies.get(i));
    }        

    if (entity != null) {
       entity.consumeContent();
    }
    System.out.println("------------------GET-END---------------------");

    // Create a new post
    HttpPost post = new HttpPost(urlTwo);
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");

    // Add params
    HttpParams params = new BasicHttpParams();
    params.setParameter("action", "search");
    params.setParameter("word", "hello");

    post.setParams(params);

    //Execute
    HttpResponse response2 = httpClient.execute(post, localContext);
도움이 되었습니까?

해결책

이 질문에 대한 나의 대답을보십시오.

httpclient 4- 마지막 리디렉션 URL을 캡처하는 방법

다른 팁

브라우저 작업을 자동화하고 세션을 유지 관리하여 유지 관리 해야하는 세션에도 액세스 할 수 있도록해야한다고 가정합니다.

org.apache.http.client api를 통해이 방법을 모르겠습니다. org.apache.http.client API를 사용하는 것으로 제한되지 않고 다른 API를 사용할 수 있다면 사용할 수 있습니다. htmlunit API는 그렇지 않으면 나머지 답변을 무시할 수 있습니다.

세션 유지 및 브라우저 작동 자동화 htmlunit 다음과 같이 수행 할 수 있습니다.

import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;

final WebClient webClient = new WebClient();
    try {
        webClient.setJavaScriptEnabled(true);
        webClient.setThrowExceptionOnScriptError(false);
        webClient.setCssEnabled(true);
        webClient.setUseInsecureSSL(true);
        webClient.setRedirectEnabled(true);

        HtmlPage loginPage = webClient.getPage(new URL("https://www.orkut.com/"));
        System.out.println(loginPage.getTitleText());
        List<HtmlForm> forms = loginPage.getForms();
        HtmlForm loginForm = forms.get(0);
        HtmlTextInput username = loginForm.getInputByName("Email");
        HtmlPasswordInput password = loginForm.getInputByName("Passwd");
        HtmlInput submit = loginForm.getInputByName("signIn");
        username.setValueAttribute("username");
        password.setValueAttribute("password");
        HtmlPage homePage = submit.click();.
        Thread.sleep(10 * 1000);
        HtmlPage homePageFrame = (HtmlPage) homePage.getFrameByName("orkutFrame").getEnclosedPage();
        HtmlPage communitiesTestPage = (HtmlPage) webClient.openWindow(new URL("http://www.orkut.co.in/Main#Community?cmm=1"), "CommunitiesWindow").getEnclosedPage();
    }catch(java.security.GeneralSecurityException e) {
        e.printStackTrace();
    }catch(java.io.IOException e) {
        e.printStackTrace();
    }catch(InterruptedException e) {
        e.printStackTrace();
    }

    WebWindow ww = webClient.getWebWindowByName("CommunitiesWindow");
    WebRequestSettings wrs1 = new WebRequestSettings(URL); // URL is the url that requires authentication first

위의 코드가 브라우저 작동을 자동화하는 방법과 세션을 자동으로 유지하는 방법을 알 수 있습니다. 쿠키 나 urlredirect를 수동으로 처리 할 필요가 없습니다 ...

Java에서 나온 간단한 방법이 있습니다. 다음 단계는 다음과 같습니다.

  1. httpurl 연결을 만듭니다.
  2. 세트 HttpURLConnection.setFollowRedirects( true ); // 기본적으로 사실이어야합니다
  3. HTTPURLConnection 객체를 통해 연결을 호출하십시오.
  4. 연결 후 getHeadersFields() httpurlconnection 객체를 통해;
  5. 호출하여 리디렉션 된 URL을 가져옵니다 getUrl() 위의 httpurlconnection 객체를 통해;

HTTP 헤더에서 위치 필드를 사용하여 가져 오는 또 다른 방법이 있지만 때로는 헤더에 위치 필드를 얻지 못합니다. 적어도 나에게는 효과가 없었습니다. 그러나 위의 방법은 확실히 작동합니다.

이용 가능합니다 location 헤더.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top