Example usage for org.apache.commons.httpclient HttpMethod setFollowRedirects

List of usage examples for org.apache.commons.httpclient HttpMethod setFollowRedirects

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setFollowRedirects.

Prototype

public abstract void setFollowRedirects(boolean paramBoolean);

Source Link

Usage

From source file:com.discursive.jccook.httpclient.RedirectExample.java

public static void main(String[] args) throws HttpException, IOException {
    // Configure Logging
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");

    HttpClient client = new HttpClient();
    String url = "http://www.discursive.com/cgi-bin/jccook/redirect.cgi";

    System.out.println("Executing Method not following redirects: ");
    HttpMethod method = new GetMethod(url);
    method.setFollowRedirects(false);
    executeMethod(client, method);//from  w  ww  .  j a v  a  2s.  c  o m

    System.out.println("Executing Method following redirects: ");
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    executeMethod(client, method);
}

From source file:TrivialApp.java

public static void main(String[] args) {
    if ((args.length != 1) && (args.length != 3)) {
        printUsage();/*from w w  w. j  a va2 s .c om*/
        System.exit(-1);
    }

    Credentials creds = null;
    if (args.length >= 3) {
        creds = new UsernamePasswordCredentials(args[1], args[2]);
    }

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 5 seconds
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    //set the default credentials
    if (creds != null) {
        client.getState().setCredentials(AuthScope.ANY, creds);
    }

    String url = args[0];
    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();

    System.exit(0);
}

From source file:ExampleP2PHttpClient.java

public static void main(String[] args) {
    // initialize JXTA
    try {/*from ww w.j  a v a2s . c o  m*/
        // sign in and initialize the JXTA network; profile this peer and create it
        // if it doesn't exist
        P2PNetwork.signin("clientpeer", "clientpeerpassword", "TestNetwork", true);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    // register the P2P socket protocol factory
    Protocol jxtaHttp = new Protocol("p2phttp", new P2PProtocolSocketFactory(), 80);
    Protocol.registerProtocol("p2phttp", jxtaHttp);

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 50 seconds
    client.setConnectionTimeout(50000);

    String url = System.getProperty("url");
    if (url == null || url.equals("")) {
        System.out.println("You must provide a URL to access.  For example:");
        System.out.println("ant example-webclient-run -D--url=p2phttp://www.somedomain.foo");

        System.exit(1);
    }
    System.out.println("Connecting to " + url + "...");

    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    method.setStrictMode(false);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();
    method.recycle();

    System.exit(0);
}

From source file:fr.dutra.confluence2wordpress.util.UrlUtils.java

private static URI followRedirectsInternal(URI url, int maxRedirections) {
    URI response = url;/*w ww .j av a 2 s .c om*/
    HttpClient client = new HttpClient();
    DefaultHttpMethodRetryHandler handler = new DefaultHttpMethodRetryHandler(1, false);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, handler);
    HttpMethod method = new HeadMethod(url.toASCIIString());
    //method.setRequestHeader("Accept-Language", locale.getLanguage() + ",en");
    method.setFollowRedirects(false);
    try {
        int statusCode = client.executeMethod(method);
        if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY) | (statusCode == HttpStatus.SC_MOVED_TEMPORARILY)) {
            if (maxRedirections > 0) {
                Header location = method.getResponseHeader("Location");
                if (!location.getValue().equals("")) {
                    // recursively check URL until it's not redirected any more
                    // locations can be relative to previous URL
                    URI target = url.resolve(location.getValue());
                    response = followRedirectsInternal(target, maxRedirections - 1);
                }
            }
        }
    } catch (Exception e) {
        //HttpClient can also throw IllegalArgumentException when URLs are malformed
    }
    return response;
}

From source file:lucee.commons.net.http.httpclient3.HttpMethodCloner.java

/**
* Clones a HttpMethod. &ltbr>/*from   w ww  .j av a2 s .  co  m*/
* &ltb&gtAttention:</b> You have to clone a method before it has
* been executed, because the URI can change if followRedirects
* is set to true.
*
* @param m the HttpMethod to clone
*
* @return the cloned HttpMethod, null if the HttpMethod could
* not be instantiated
*
* @throws java.io.IOException if the request body couldn't be read
*/
public static HttpMethod clone(HttpMethod m) {
    HttpMethod copy = null;
    try {
        copy = m.getClass().newInstance();
    } catch (InstantiationException iEx) {
    } catch (IllegalAccessException iaEx) {
    }
    if (copy == null) {
        return null;
    }
    copy.setDoAuthentication(m.getDoAuthentication());
    copy.setFollowRedirects(m.getFollowRedirects());
    copy.setPath(m.getPath());
    copy.setQueryString(m.getQueryString());

    Header[] h = m.getRequestHeaders();
    int size = (h == null) ? 0 : h.length;

    for (int i = 0; i < size; i++) {
        copy.setRequestHeader(new Header(h[i].getName(), h[i].getValue()));
    }
    copy.setStrictMode(m.isStrictMode());
    if (m instanceof HttpMethodBase) {
        copyHttpMethodBase((HttpMethodBase) m, (HttpMethodBase) copy);
    }
    if (m instanceof EntityEnclosingMethod) {
        copyEntityEnclosingMethod((EntityEnclosingMethod) m, (EntityEnclosingMethod) copy);
    }
    return copy;
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

/**
  * Execute a HTTTP Client and follow redirect over different hosts
  * @param client//w  ww.  j ava  2s .  c  o m
  * @param method
  * @param doRedirect
  * @return
  * @throws IOException
  * @throws HttpException
  */
public static HttpMethod execute(HttpClient client, HttpMethod method, int maxRedirect)
        throws HttpException, IOException {
    short count = 0;
    method.setFollowRedirects(false);

    while (isRedirect(client.executeMethod(method)) && count++ < maxRedirect) {
        method = rewrite(method);
    }
    return method;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute given url, manually follow redirects.
 * Workaround for HttpClient bug (GET full URL over HTTPS and proxy)
 *
 * @param httpClient HttpClient instance
 * @param url        url string//www .  j  a  v a  2s  .  c om
 * @return executed method
 * @throws IOException on error
 */
public static HttpMethod executeFollowRedirects(HttpClient httpClient, String url) throws IOException {
    HttpMethod method = new GetMethod(url);
    method.setFollowRedirects(false);
    return executeFollowRedirects(httpClient, method);
}

From source file:gov.loc.ndmso.proxyfilter.RequestProxy.java

private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl)
        throws IOException {
    final String methodName = hsRequest.getMethod();
    final HttpMethod method;
    if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod postMethod = new PostMethod();
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(
                hsRequest.getInputStream());
        postMethod.setRequestEntity(inputStreamRequestEntity);
        method = postMethod;/*from   w ww.  j ava  2 s .  c  o m*/
    } else if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod();
    } else {
        // log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod());
        return null;
    }

    method.setFollowRedirects(false);
    method.setPath(targetUrl.getPath());
    method.setQueryString(targetUrl.getQuery());

    @SuppressWarnings("unchecked")
    Enumeration<String> e = hsRequest.getHeaderNames();
    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = e.nextElement();
            if ("host".equalsIgnoreCase(headerName)) {
                //the host value is set by the http client
                continue;
            } else if ("content-length".equalsIgnoreCase(headerName)) {
                //the content-length is managed by the http client
                continue;
            } else if ("accept-encoding".equalsIgnoreCase(headerName)) {
                //the accepted encoding should only be those accepted by the http client.
                //The response stream should (afaik) be deflated. If our http client does not support
                //gzip then the response can not be unzipped and is delivered wrong.
                continue;
            } else if (headerName.toLowerCase().startsWith("cookie")) {
                //fixme : don't set any cookies in the proxied request, this needs a cleaner solution
                continue;
            }

            @SuppressWarnings("unchecked")
            Enumeration<String> values = hsRequest.getHeaders(headerName);
            while (values.hasMoreElements()) {
                String headerValue = values.nextElement();
                // log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue);
                method.addRequestHeader(headerName, headerValue);
            }
        }
    }

    // add rs5/tomcat5 request header for ML
    method.addRequestHeader("X-Via", "tomcat5");

    // log.info("proxy query string " + method.getQueryString());
    return method;
}

From source file:com.ibm.watson.apis.conversation_enhanced.filters.LookUp.java

private HttpMethod getHttpMethod(String url) {
    HttpMethod method = new GetMethod(url);
    method.setFollowRedirects(true);
    return method;
}

From source file:com.knowledgebooks.rdf.SparqlClient.java

public SparqlClient(String endpoint_URL, String sparql) throws Exception {
    //System.out.println("SparqlClient("+endpoint_URL+", "+sparql+")");
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);

    String req = URLEncoder.encode(sparql, "utf-8");
    HttpMethod method = new GetMethod(endpoint_URL + "?query=" + req);
    method.setFollowRedirects(false);
    try {/* www.  ja v  a  2s.c om*/
        client.executeMethod(method);
        //System.out.println(method.getResponseBodyAsString());
        //if (true) return;
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + endpoint_URL + "'");
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + endpoint_URL + "'");
    }
    method.releaseConnection();
}