Example usage for org.apache.commons.httpclient HttpClient executeMethod

List of usage examples for org.apache.commons.httpclient HttpClient executeMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient executeMethod.

Prototype

public int executeMethod(HostConfiguration paramHostConfiguration, HttpMethod paramHttpMethod)
              throws IOException, HttpException 

Source Link

Usage

From source file:HttpClientParameter.java

public static void main(String args[]) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "My Browser");

    HostConfiguration host = client.getHostConfiguration();
    host.setHost("www.google.com");

    GetMethod method = new GetMethod("http://www.yahoo.com");

    int returnCode = client.executeMethod(host, method);

    System.err.println(method.getResponseBodyAsString());

    System.err//from w  w w  .j a  v a 2  s  .co m
            .println("User-Agent: " + method.getHostConfiguration().getParams().getParameter("http.useragent"));

    System.err.println("User-Agent: " + method.getParams().getParameter("http.useragent"));

    method.releaseConnection();
}

From source file:BasicAuthenticationExecuteJSPMethod.java

public static void main(String args[]) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("parameterKey", "value");

    HostConfiguration host = client.getHostConfiguration();
    host.setHost(new URI("http://localhost:8080", true));

    GetMethod method = new GetMethod("/commons/folder/protected.jsp");
    try {//from   ww w.  j av  a2 s.c o m
        client.executeMethod(host, method);
        System.err.println(method.getStatusLine());
        System.err.println(method.getResponseBodyAsString());
    } catch (Exception e) {
        System.err.println(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:BasicAuthenticationForJSPPage.java

public static void main(String args[]) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "My Browser");

    HostConfiguration host = client.getHostConfiguration();
    host.setHost(new URI("http://localhost:8080", true));

    Credentials credentials = new UsernamePasswordCredentials("tomcat", "tomcat");
    AuthScope authScope = new AuthScope(host.getHost(), host.getPort());
    HttpState state = client.getState();
    state.setCredentials(authScope, credentials);

    GetMethod method = new GetMethod("/commons/chapter01/protected.jsp");
    try {// ww w  .  jav  a2  s .c o  m
        client.executeMethod(host, method);
        System.err.println(method.getStatusLine());
        System.err.println(method.getResponseBodyAsString());
    } catch (Exception e) {
        System.err.println(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:Correct.java

public static void main(String[] args) {

    String URLL = "";
    HttpClient client = new HttpClient();
    HttpMethod method = new PostMethod(URLL);
    method.setDoAuthentication(true);//from w  w w.ja va  2  s  .com
    HostConfiguration hostConfig = client.getHostConfiguration();
    hostConfig.setHost("172.29.38.8");
    hostConfig.setProxy("172.29.90.4", 8);
    //   NTCredentials proxyCredentials = new NTCredentials("", "", "", "");
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("", ""));
    ////        try {
    ////            URL url = new URL("");
    ////            HttpURLConnection urls = (HttpURLConnection) url.openConnection();
    ////            
    ////           
    ////        } catch (MalformedURLException ex) {
    ////            Logger.getLogger(Correct.class.getName()).log(Level.SEVERE, null, ex);
    ////        } catch (IOException ex) {
    ////            Logger.getLogger(Correct.class.getName()).log(Level.SEVERE, null, ex);
    ////        }
    try {
        // send the transaction
        client.executeMethod(hostConfig, method);
        StatusLine status = method.getStatusLine();

        if (status != null && method.getStatusCode() == 200) {

            System.out.println(method.getResponseBodyAsString() + "\n Status code : " + status);

        } else {

            System.err.println(method.getStatusLine() + "\n: Posting Failed !");
        }

    } catch (IOException ioe) {

        ioe.printStackTrace();

    }
    method.releaseConnection();

}

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

/**
 * This method performs the proxying of the request to the target address.
 *
 * @param target     The target address. Has to be a fully qualified address. The request is send as-is to this address.
 * @param hsRequest  The request data which should be send to the
 * @param hsResponse The response data which will contain the data returned by the proxied request to target.
 * @throws java.io.IOException Passed on from the connection logic.
 *///ww  w . ja v  a2s.  c o m
public static void execute(final String target, final String collection, final HttpServletRequest hsRequest,
        final HttpServletResponse hsResponse, MultiThreadedHttpConnectionManager connManager)
        throws IOException {
    // log.info("execute, target is " + target);
    // log.info("response commit state: " + hsResponse.isCommitted());

    if (target == null || "".equals(target) || "".equals(target.trim())) {
        log.error("The target address is not given. Please provide a target address.");
        return;
    }

    // log.info("checking url");
    final URL url;
    try {
        url = new URL(target);
    } catch (MalformedURLException e) {
        // log.error("The provided target url is not valid.", e);
        return;
    }

    // log.info("setting up the host configuration");

    final HostConfiguration config = new HostConfiguration();

    ProxyHost proxyHost = getUseProxyServer((String) hsRequest.getAttribute("use-proxy"));
    if (proxyHost != null)
        config.setProxyHost(proxyHost);

    final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort();
    config.setHost(url.getHost(), port, "http");

    // log.info("config is " + config.toString());

    final HttpMethod targetRequest = setupProxyRequest(hsRequest, url);
    if (targetRequest == null) {
        // log.error("Unsupported request method found: " + hsRequest.getMethod());
        return;
    }

    //perform the request to the target server
    final HttpClient client = new HttpClient(connManager);
    //if (log.isInfoEnabled()) {
    // log.info("client state" + client.getState());
    // log.info("client params" + client.getParams().toString());
    // log.info("executeMethod / fetching data ...");
    //}

    final int result = client.executeMethod(config, targetRequest);

    //copy the target response headers to our response
    setupResponseHeaders(targetRequest, hsResponse);

    String binRegex = ".*\\.(?i)(jpg|tif|png|gif|bmp|mp3|mpg)(.*$)*";
    String binRegexRedux = ".*(?i)(\\/thumb)(.*$)*";

    if (target.matches(binRegex) || target.matches(binRegexRedux)) {
        // log.info("binRegex matched: " + target);
        InputStream originalResponseStream = targetRequest.getResponseBodyAsStream();

        if (originalResponseStream != null) {

            if (targetRequest.getResponseHeaders().toString().matches("(?i).*content-type.*")) {
                PrintWriter responseStream = hsResponse.getWriter();
                copyStreamText(targetRequest.getResponseBodyAsString(), responseStream);
            } else {
                OutputStream responseStream = hsResponse.getOutputStream();
                copyStreamBinary(originalResponseStream, responseStream);
            }
        }

    } else {
        // log.info("binRegex NOT matched: " + target);
        String proxyResponseStr = targetRequest.getResponseBodyAsString();
        // the body might be null, i.e. for responses with cache-headers which leave out the body

        if (proxyResponseStr != null) {
            //proxyResponseStr = proxyResponseStr.replaceAll("xqy", "jsp");

            proxyResponseStr = proxyResponseStr.replaceAll("National Library Catalog",
                    "Library of Congress Data Service");
            proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress collections",
                    "Library of Congress bibliographic data");
            proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress Collections",
                    "Library of Congress Bibliographic Data");

            proxyResponseStr = proxyResponseStr.replaceAll("action=\"/", "action=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("href=\"/", "href=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("href=\"/diglib/loc\\.",
                    "href=\"/diglib/" + collection + "/loc.");
            proxyResponseStr = proxyResponseStr.replaceAll("src=\"/", "src=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("value=\"/", "value=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("url\\(/", "url\\(/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("url\\(\"/", "url\\(\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("src'\\) == \"/", "src'\\) == \"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("src\", \"/", "src\", \"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("natlibcat@loc.gov", "ndmso@loc.gov");

            proxyResponseStr = proxyResponseStr.replaceAll("/nlc/", "/lcds/");
            proxyResponseStr = proxyResponseStr.replaceAll("/lcwa/", "/lcwanew/");
            //proxyResponseStr = proxyResponseStr.replaceAll("/tohap/", "/x-tohap/");

            proxyResponseStr = proxyResponseStr.replaceAll(".xqy", ".jsp");

            PrintWriter responseStream = hsResponse.getWriter();
            copyStreamText(proxyResponseStr, responseStream);
        }
    }

    // log.info("set up response, result code was " + result);
    targetRequest.releaseConnection();

    // SimpleHttpConnectionManager connManager = (SimpleHttpConnectionManager) client.getHttpConnectionManager();
    // connManager.closeIdleConnections(1000);

    // HttpConnection httpConn = connManager.getConnection(config);
    // httpConn.releaseConnection();

}

From source file:com.urswolfer.intellij.plugin.gerrit.rest.SslSupport.java

@Nullable
private static HttpMethod handleCertificateExceptionAndRetry(@NotNull IOException e, @NotNull String host,
        @NotNull HttpClient client, @NotNull URI uri,
        @NotNull ThrowableConvertor<String, HttpMethod, IOException> methodCreator) throws IOException {
    if (!isCertificateException(e)) {
        throw e;//w  w w  .ja  v a2  s .  co m
    }

    if (isTrusted(host)) {
        // creating a special configuration that allows connections to non-trusted HTTPS hosts
        // see the javadoc to EasySSLProtocolSocketFactory for details
        Protocol easyHttps = new Protocol("https", (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(),
                443);
        HostConfiguration hc = new HostConfiguration();
        hc.setHost(host, 443, easyHttps);
        String relativeUri = new URI(uri.getPathQuery(), false).getURI();
        // it is important to use relative URI here, otherwise our custom protocol won't work.
        // we have to recreate the method, because HttpMethod#setUri won't overwrite the host,
        // and changing host by hands (HttpMethodBase#setHostConfiguration) is deprecated.
        HttpMethod method = methodCreator.convert(relativeUri);
        client.executeMethod(hc, method);
        return method;
    }
    throw e;
}