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

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

Introduction

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

Prototype

public HttpClient() 

Source Link

Usage

From source file:com.honnix.cheater.network.CheaterHttpClient.java

private void initHttpClient() {
    httpClient = new HttpClient();

    httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    httpClient.getParams().setParameter("http.useragent", CheaterConstant.USER_AGENT);
    httpClient.getParams().setParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, Boolean.TRUE);
}

From source file:it.geosolutions.figis.requester.HTTPUtils.java

/**
* Performs an HTTP GET on the given URL.
* <BR>Basic auth is used if both username and pw are not null.
*
* @param url The URL where to connect to.
* @param username Basic auth credential. No basic auth if null.
* @param pw Basic auth credential. No basic auth if null.
* @return The HTTP response as a String if the HTTP response code was 200 (OK).
* @throws MalformedURLException//from   ww w .  j a va 2 s.  c  om
*/
public static String get(String url, String username, String pw) throws MalformedURLException {
    GetMethod httpMethod = null;
    try {
        HttpClient client = new HttpClient();
        setAuth(client, url, username, pw);
        httpMethod = new GetMethod(url);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        int status = client.executeMethod(httpMethod);
        if (status == HttpStatus.SC_OK) {
            InputStream is = httpMethod.getResponseBodyAsStream();
            String response = IOUtils.toString(is);
            if (response.trim().length() == 0) // sometime gs rest fails
            {
                LOGGER.warn("ResponseBody is empty");

                return null;
            } else {
                return response;
            }
        } else {
            LOGGER.info("(" + status + ") " + HttpStatus.getStatusText(status) + " -- " + url);
        }
    } catch (ConnectException e) {
        LOGGER.error("Couldn't connect to [" + url + "]", e);
    } catch (IOException e) {
        LOGGER.error("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }

    return null;
}

From source file:com.intuit.tank.http.binary.BinaryRequestTest.java

/**
 * Run the void setConvertData() method test.
 *
 * @throws Exception//w  w w  .  j  a va  2s  . c om
 *
 * @generatedBy CodePro at 12/16/14 3:57 PM
 */
@Test
public void testSetConvertData_2() throws Exception {
    BinaryRequest fixture = new BinaryRequest(new HttpClient());

    fixture.setConvertData();

    // An unexpected exception was thrown in user code while executing this test:
    //    java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.httpclient.HttpClient
}

From source file:com.predic8.membrane.core.interceptor.balancer.ClusterNotificationInterceptorTest.java

@Test
public void testUpEndpoint() throws Exception {
    GetMethod get = new GetMethod("http://localhost:3002/clustermanager/up?"
            + createQueryString("host", "node1.clustera", "port", "3018", "cluster", "c1"));

    assertEquals(204, new HttpClient().executeMethod(get));
    assertEquals("node1.clustera",
            BalancerUtil.lookupBalancer(router, "Default").getAllNodesByCluster("c1").get(0).getHost());

}

From source file:com.ltasks.BaseClient.java

/**
 * Creates a new BaseClient.//from   w w w . j  ava 2  s. c om
 * 
 * @param aApiKey
 *            the user api key
 * @param aIsIncludeSource
 *            if to include the source text (default is true)
 * @param aIsGZipContentEncoding
 *            if true will gzip contents to communicate with server (default
 *            is true)
 * @throws IllegalArgumentException
 *             the api key does not conform with the standard
 *             representation.
 */
public BaseClient(String aApiKey, boolean aIsIncludeSource, boolean aIsGZipContentEncoding)
        throws IllegalArgumentException {
    validateApiKey(aApiKey);
    mApiKey = aApiKey;
    client = new HttpClient();
    client.getParams().setParameter("http.useragent", "ltasks4j/0.0.3");
    mIsIncludeSource = aIsIncludeSource;
    mIsGZipContentEncoding = aIsGZipContentEncoding;
}

From source file:de.linsin.alterego.notification.AppNotificationService.java

HttpClient setUp() {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HTTP_USERAGENT, "IRC Bot");
    return client;
}

From source file:com.thoughtworks.go.agent.functional.X509CertificateTest.java

@Test
public void shouldSaveCertificateInAgentTrustStore() throws Exception {
    Protocol authhttps = new Protocol("https", protocolSocketFactory, sslPort);
    Protocol.registerProtocol("https", authhttps);
    HttpClient client = new HttpClient();
    GetMethod httpget = new GetMethod("https://localhost:" + sslPort + "/go/");
    client.executeMethod(httpget);/* w  w w.  j  av a2s  .com*/
    assertTrue("Should have created trust store", truststore.exists());
}

From source file:com.arjuna.qa.junit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {/* www.j a va  2  s .  c  o m*/
        System.err.println("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        System.err.println("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        System.err.println("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        System.err.println(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:com.mrfeinberg.translation.AbstractTranslationService.java

public Runnable translate(final String phrase, final LanguagePair lp, final TranslationListener listener) {
    final Language b = lp.b();

    final HttpClient httpClient = new HttpClient();
    if (proxyPrefs.getUseProxy()) {
        httpClient.getHostConfiguration().setProxy(proxyPrefs.getProxyHost(), proxyPrefs.getProxyPort());
    }//from   w ww  . j a va2 s. co m

    final HttpMethod httpMethod = getHttpMethod(phrase, lp);
    final Callable<String> callable = new Callable<String>() {
        public String call() throws Exception {
            int result = httpClient.executeMethod(httpMethod);
            if (result != 200) {
                throw new Exception("Got " + result + " status for " + httpMethod.getURI());
            }
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpMethod.getResponseBodyAsStream(), "utf8"));
            try {
                final StringBuilder sb = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null)
                    sb.append(line);
                return sb.toString();
            } finally {
                in.close();
                httpMethod.releaseConnection();
            }
        }
    };
    final FutureTask<String> tc = new FutureTask<String>(callable);
    return new Runnable() {
        public void run() {
            try {
                executor.execute(tc);
                final String result = tc.get(timeout, TimeUnit.MILLISECONDS);
                String found = findTranslatedText(result);
                if (found == null) {
                    listener.error("Cannot find translated text in result.");
                } else {
                    found = found.replaceAll("\\s+", " ");
                    listener.result(found, b);
                }
            } catch (final TimeoutException e) {
                listener.timedOut();
            } catch (final InterruptedException e) {
                listener.cancelled();
            } catch (final Exception e) {
                e.printStackTrace();
                listener.error(e.toString());
            }
        }
    };
}

From source file:edu.unc.lib.dl.admin.controller.RESTProxyController.java

@RequestMapping(value = { "/services/rest", "/services/rest/*", "/services/rest/**/*" })
public final void proxyAjaxCall(HttpServletRequest request, HttpServletResponse response) throws IOException {
    log.debug("Prepending service url " + this.servicesUrl + " to " + request.getRequestURI());
    String url = request.getRequestURI().replaceFirst(".*/services/rest/?", this.servicesUrl);
    if (request.getQueryString() != null)
        url = url + "?" + request.getQueryString();

    OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
    HttpClient client = new HttpClient();
    HttpMethod method = null;/*from   w w  w  .  j a v  a 2s.c om*/
    try {
        log.debug("Proxying ajax request to services REST api via " + request.getMethod());
        // Split this according to the type of request
        if (request.getMethod().equals("GET")) {
            method = new GetMethod(url);
        } else if (request.getMethod().equals("POST")) {
            method = new PostMethod(url);
            // Set any eventual parameters that came with our original
            // request (POST params, for instance)
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                ((PostMethod) method).setParameter(paramName, request.getParameter(paramName));
            }
        } else {
            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Forward the user's groups along with the request
        method.addRequestHeader(HttpClientUtil.SHIBBOLETH_GROUPS_HEADER, GroupsThreadStore.getGroupString());
        method.addRequestHeader("On-Behalf-Of", GroupsThreadStore.getUsername());

        // Execute the method
        client.executeMethod(method);

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {
            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }
        }
        try (InputStream responseStream = method.getResponseBodyAsStream()) {
            int b;
            while ((b = responseStream.read()) != -1) {
                response.getOutputStream().write(b);
            }
        }
        response.getOutputStream().flush();
    } catch (HttpException e) {
        writer.write(e.toString());
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        writer.write(e.toString());
        throw e;
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}