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:net.sf.ehcache.constructs.web.filter.SpeedTest.java

/**
 * Time to get 200 Cached Pages/* w  w  w  .  j  a  va  2 s  .c  om*/
 * StopWatch time: 947ms
 */
public void testSpeedHttpClientNotCached() throws IOException {
    StopWatch stopWatch = new StopWatch();
    String url = "http://localhost:9080/Login.jsp";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    stopWatch.getElapsedTime();
    for (int i = 0; i < 200; i++) {
        httpClient.executeMethod(httpMethod);
        httpMethod.getResponseBodyAsStream();
    }
    long time = stopWatch.getElapsedTime();
    LOG.info("Time for 200 uncached page requests: " + time);
}

From source file:net.bioclipse.cir.business.CirManager.java

public ICDKMolecule getByName(String name) throws BioclipseException {
    HttpClient client = new HttpClient();
    String fullURL = SERVICE + name + "/sdf";
    System.out.println(("URL: " + fullURL));
    GetMethod method = new GetMethod(fullURL);
    addMethodHeaders(method, new HashMap<String, String>() {
        {/*  w w w  .  j a  va  2  s.c  om*/
            put("Accept", "text/plain");
        }
    });
    try {
        client.executeMethod(method);
        String content = method.getResponseBodyAsString();
        if (content.contains("http://www.w3.org/1999/xhtml")) {
            throw new BioclipseException("HTML page returned: probably multiple search hits");
        }
        InputStream reader = method.getResponseBodyAsStream();
        return cdk.loadMolecule(reader, (IChemFormat) MDLV2000Format.getInstance(), null, null);
    } catch (HttpException exception) {
        throw new BioclipseException("Error while accessing CIR: " + exception.getMessage(), exception);
    } catch (IOException exception) {
        throw new BioclipseException("Error while reading the CIR response: " + exception.getMessage(),
                exception);
    }
}

From source file:net.bioclipse.opentox.api.Task.java

public static void delete(String task) throws IOException, GeneralSecurityException {
    HttpClient client = new HttpClient();
    DeleteMethod method = new DeleteMethod(task);
    method.getParams().setParameter("http.socket.timeout", new Integer(Activator.TIME_OUT));
    client.executeMethod(method);//from   w w  w  . j a  va  2 s .c  o  m
    int status = method.getStatusCode();
    switch (status) {
    case 200:
        // excellent, it worked
        break;
    case 401:
        throw new GeneralSecurityException("Not authorized");
    case 404:
        // not found, well, I guess equals 'deleted'
        break;
    case 503:
        throw new IOException("Service unavailable");
    default:
        throw new IOException("Unknown server state: " + status);
    }
}

From source file:com.bt.aloha.batchtest.v2.scenarios.CreateCallTerminateCallScenario.java

public void run(String scenarioId) {
    HttpClient httpClient = new HttpClient();

    String makeCallAddress = String.format("http://%s/SpringRing/makeCall?caller=%s&callee=%s",
            getHttpEndpoint(), getTestEndpoint(), getTestEndpoint());

    HttpMethod makeCallMethod = new GetMethod(makeCallAddress);
    ScenarioRunResult runResult = new ScenarioRunResult(scenarioId, this.getName());
    try {/*from  w  ww  . j  a v a 2 s  .  c  o m*/
        log.debug("Executing GET on " + makeCallAddress);
        acquireSyncSemaphore();
        int result = httpClient.executeMethod(makeCallMethod);
        log.debug("GET returned " + result);
        if (result != 200) {
            runResult.setResult(false,
                    String.format("HTTP %d received from host when calling makeCall", result));
            log.error(makeCallMethod.getResponseBodyAsString());
        } else {
            String resultString = makeCallMethod.getResponseBodyAsString();
            Properties makeCallResult = new Properties();
            makeCallResult.load(new ByteArrayInputStream(resultString.getBytes()));
            String callId = makeCallResult.getProperty("callid", null);
            log.debug("result from makeCall " + callId);

            String terminateCallAddress = "http://%s/SpringRing/terminateCall?callid=%s";
            HttpMethod terminateCallMethod = new GetMethod(
                    String.format(terminateCallAddress, getHttpEndpoint(), callId));
            result = httpClient.executeMethod(terminateCallMethod);
            resultString = terminateCallMethod.getResponseBodyAsString();
            Properties terminateCallResult = new Properties();
            terminateCallResult.load(new ByteArrayInputStream(resultString.getBytes()));
            log.debug("result from terminateCall " + result);
            if (result != 200) {
                runResult.setResult(false,
                        String.format("HTTP %d received from host when calling terminateCall", result));
                log.error(terminateCallMethod.getResponseBodyAsString());
            } else {
                String makeLocalHostName = makeCallResult.getProperty("local.host.name");
                String termLocalHostName = terminateCallResult.getProperty("local.host.name");
                Map<String, String> data = new HashMap<String, String>();
                data.put("make", makeLocalHostName);
                data.put("terminate", termLocalHostName);
                runResult.setResult(true, "OK", data);
            }
        }
    } catch (Throwable e) {
        e.printStackTrace();
        runResult.setResult(false, String.format("Exception %s", e.getMessage()));
    } finally {
        publishResultOnScenarioComplete(runResult);
    }
}

From source file:io.sightly.tck.http.Client.java

/**
 * Creates a basic HTTP client.//  www.j  a v a2 s.co m
 */
public Client() {
    client = new HttpClient();
    client.getHttpConnectionManager().setParams(prepareDefaultClientParameters());
    DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(3, true);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
}

From source file:edu.stanford.muse.webapp.HTMLToImage.java

/**
 * Convert an HTML page at the specified URL into an image who's data is
 * written to the provided output stream.
 *
 * @param url    URL to the page that is to be imaged.
 * @param os     An output stream that is to be opened for writing.  Image
 *               data will be written to the provided stream.  The stream
 *               will not be closed under any circumstances by this method.
 * @param width  The desired width of the image that will be created.
 * @param height The desired height of the image that will be created.
 *
 * @returns true if the page at the provided URL was loaded, converted to an
 *          image, and the image data has been written to the output stream,
 *          false if an error has ocurred along the way.
 *
 * @throws HTMLImagerException if an error has ocurred.
 *///from  w  w w .j a v  a  2 s  .  c  om
public static boolean image(String url, OutputStream os, int width, int height) {
    if (log.isDebugEnabled())
        log.debug("Imaging url '" + url + "'.");

    boolean successful = false;

    try {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);

        httpClient.executeMethod(getMethod);

        int httpStatus = getMethod.getStatusCode();

        if (httpStatus == HttpServletResponse.SC_OK) {
            Tidy tidy = new Tidy();

            tidy.setQuiet(true);
            tidy.setXHTML(true);
            tidy.setHideComments(true);
            tidy.setInputEncoding("UTF-8");
            tidy.setOutputEncoding("UTF-8");
            tidy.setShowErrors(0);
            tidy.setShowWarnings(false);

            Document doc = tidy.parseDOM(getMethod.getResponseBodyAsStream(), null);

            if (doc != null) {
                BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = (Graphics2D) buf.getGraphics();
                Graphics2DRenderer renderer = new Graphics2DRenderer();
                SharedContext context = renderer.getSharedContext();
                UserAgentCallback userAgent = new HTMLImagerUserAgent(url);

                context.setUserAgentCallback(userAgent);
                context.setNamespaceHandler(new XhtmlNamespaceHandler());

                renderer.setDocument(doc, url);
                renderer.layout(graphics, new Dimension(width, height));
                renderer.render(graphics);
                graphics.dispose();

                /*
                JPEGEncodeParam param = JPEGCodec.getDefaultJPEGEncodeParam( buf );
                        
                param.setQuality( (float)1.0, false );
                        
                JPEGImageEncoder imageEncoder = JPEGCodec.createJPEGEncoder( os,
                      param );
                        
                imageEncoder.encode( buf );
                */
                successful = true;
            } else {
                if (log.isDebugEnabled())
                    log.debug("Unable to image URL '" + url
                            + "'.  The HTML that was returned could not be tidied.");
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Unable to image URL '" + url + "'.  Server returned status code '" + httpStatus
                        + "'.");
        }
    }

    catch (Exception e) {
        throw new RuntimeException("Unable to image URL '" + url + "'.", e);
    }

    return successful;
}

From source file:com.khipu.lib.java.KhipuService.java

protected String post(Map data) throws KhipuJSONException, IOException {

    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(Khipu.API_URL + getMethodEndpoint());
    NameValuePair[] params = new NameValuePair[data.keySet().size()];

    int i = 0;// w  ww .  jav a 2  s.co m
    for (Iterator iterator = data.keySet().iterator(); iterator.hasNext(); i++) {
        String key = (String) iterator.next();
        params[i] = new NameValuePair(key, (String) data.get(key));
    }

    postMethod.setRequestBody(params);

    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (client.executeMethod(postMethod) == HttpStatus.SC_OK) {
        InputStream stream = postMethod.getResponseBodyAsStream();
        String contentAsString = getContentAsString(stream);
        stream.close();
        postMethod.releaseConnection();
        return contentAsString;
    }
    InputStream stream = postMethod.getResponseBodyAsStream();
    String contentAsString = getContentAsString(stream);
    stream.close();
    postMethod.releaseConnection();
    throw new KhipuJSONException(contentAsString);
}

From source file:com.alibaba.antx.config.resource.http.HttpSession.java

public HttpSession(ResourceDriver driver) {
    super(driver);

    client = new HttpClient();

    client.getParams().setAuthenticationPreemptive(true);
    client.getParams().setParameter(CredentialsProvider.PROVIDER, new CredentialsProvider() {
        public Credentials getCredentials(AuthScheme scheme, String host, int port, boolean proxy)
                throws CredentialsNotAvailableException {
            URI uri = ResourceContext.get().getCurrentURI();
            String username = ResourceContext.get().getCurrentUsername();
            Set visitedURIs = ResourceContext.get().getVisitedURIs();
            ResourceKey key = new ResourceKey(new ResourceURI(uri));
            String message;/*from  ww w  . j  a  v  a2 s  . co m*/

            message = "\n";
            message += "Authentication required.\n";
            message += "realm: " + scheme.getRealm() + "\n";
            message += "  uri: " + uri + "\n";

            UsernamePassword up = getResourceManager().getAuthenticationHandler().authenticate(message, uri,
                    username, visitedURIs.contains(key));

            visitedURIs.add(key);

            return new UsernamePasswordCredentials(up.getUsername(), up.getPassword());
        }
    });
}

From source file:jp.primecloud.auto.zabbix.ZabbixClientFactory.java

protected HttpClient createHttpClient() {
    return new HttpClient();
}

From source file:guru.nidi.atlassian.remote.script.RemoteJira.java

public RemoteJira(String serverUrl, String username, String password) throws RpcException {
    client = new HttpClient();
    this.serverUrl = serverUrl;
    this.username = username;
    this.password = password;
    token = (String) executeImpl("login", username, password);
}