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

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

Introduction

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

Prototype

public URI(URI base, URI relative) throws URIException 

Source Link

Document

Construct a general URI with the given relative URI.

Usage

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  .  jav a 2  s.com
        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:UsingHttpClientInsideThread.java

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

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");

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

    // first Get a big file
    MethodThread bigDataThread = new MethodThread(client, host, "/big_movie.wmv");

    bigDataThread.start();/*ww w .  j ava2s  .  c o m*/

    // next try and get a small file
    MethodThread normalThread = new MethodThread(client, host, "/");

    normalThread.start();
}

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 {/*from   ww  w  . j  a  v  a2s.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:GetMethodExample.java

public static void main(String args[]) {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");
    client.getParams().setParameter("http.connection.timeout", new Integer(5000));

    GetMethod method = new GetMethod();
    FileOutputStream fos = null;/* ww w.ja v  a2  s.  c  o  m*/

    try {

        method.setURI(new URI("http://www.google.com", true));
        int returnCode = client.executeMethod(method);

        if (returnCode != HttpStatus.SC_OK) {
            System.err.println("Unable to fetch default page, status code: " + returnCode);
        }

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

        method.setURI(new URI("http://www.google.com/images/logo.gif", true));
        returnCode = client.executeMethod(method);

        if (returnCode != HttpStatus.SC_OK) {
            System.err.println("Unable to fetch image, status code: " + returnCode);
        }

        byte[] imageData = method.getResponseBody();
        fos = new FileOutputStream(new File("google.gif"));
        fos.write(imageData);

        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setHost("www.yahoo.com", null, 80, Protocol.getProtocol("http"));

        method.setURI(new URI("/", true));

        client.executeMethod(hostConfig, method);

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

    } catch (HttpException he) {
        System.err.println(he);
    } catch (IOException ie) {
        System.err.println(ie);
    } finally {
        method.releaseConnection();
        if (fos != null)
            try {
                fos.close();
            } catch (Exception fe) {
            }
    }

}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.EndpointRequestFilter.java

@Override
public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> request) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String strURL = request.getEndpoint();
    strURL = PropertyExpander.expandProperties(context, strURL);
    try {//from w w w.  j  a v  a 2  s.  c  o m
        if (StringUtils.hasContent(strURL)) {
            URI uri = new URI(strURL, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
            httpMethod.setURI(new java.net.URI(uri.getScheme(), uri.getUserinfo(), uri.getHost(), uri.getPort(),
                    (uri.getPath()) == null ? "/" : uri.getPath(), uri.getQuery(), uri.getFragment()));
        }
    } catch (Exception e) {
        SoapUI.logError(e);
    }
}

From source file:com.carrotsearch.util.httpclient.HttpUtils.java

/**
 * Opens a HTTP/1.1 connection to the given URL using the GET method, decompresses
 * compressed response streams, if supported by the server.
 * /*from  w  w w .  j a v  a  2  s.  c o m*/
 * @param url The URL to open. The URL must be properly escaped, this method will
 *            <b>not</b> perform any escaping.
 * @param params Query string parameters to be attached to the url.
 * @param headers Any extra HTTP headers to add to the request.
 * @return The {@link HttpUtils.Response} object. Note that entire payload is read and
 *         buffered so that the HTTP connection can be closed when leaving this
 *         method.
 */
public static Response doGET(String url, Collection<NameValuePair> params, Collection<Header> headers)
        throws HttpException, IOException {
    final HttpClient client = HttpClientFactory.getTimeoutingClient();
    client.getParams().setVersion(HttpVersion.HTTP_1_1);

    final GetMethod request = new GetMethod();
    final Response response = new Response();
    try {
        request.setURI(new URI(url, true));

        if (params != null) {
            request.setQueryString(params.toArray(new NameValuePair[params.size()]));
        }

        request.setRequestHeader(HttpHeaders.URL_ENCODED);
        request.setRequestHeader(HttpHeaders.GZIP_ENCODING);
        if (headers != null) {
            for (Header header : headers)
                request.setRequestHeader(header);
        }

        Logger.getLogger(HttpUtils.class).debug("GET: " + request.getURI());

        final int statusCode = client.executeMethod(request);
        response.status = statusCode;

        InputStream stream = request.getResponseBodyAsStream();
        final Header encoded = request.getResponseHeader("Content-Encoding");
        if (encoded != null && "gzip".equalsIgnoreCase(encoded.getValue())) {
            stream = new GZIPInputStream(stream);
            response.compression = COMPRESSION_GZIP;
        } else {
            response.compression = COMPRESSION_NONE;
        }

        final Header[] respHeaders = request.getResponseHeaders();
        response.headers = new String[respHeaders.length][];
        for (int i = 0; i < respHeaders.length; i++) {
            response.headers[i] = new String[] { respHeaders[i].getName(), respHeaders[i].getValue() };
        }

        response.payload = StreamUtils.readFullyAndClose(stream);
        return response;
    } finally {
        request.releaseConnection();
    }
}

From source file:gov.nih.nci.cabio.portal.portlet.RESTProxyServletController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    try {//from   w ww.  ja  va 2  s.  com
        String relativeURL = request.getParameter("relativeURL");
        if (relativeURL == null) {
            log.error("Null relativeURL parameter");
            return null;
        }

        String qs = request.getQueryString();
        if (qs == null) {
            qs = "";
        }

        qs = qs.replaceFirst("relativeURL=(.*?)&", "");
        qs = URLDecoder.decode(qs, "UTF-8");

        String url = caBIORestURL + relativeURL + "?" + qs;
        log.info("Proxying URL: " + url);

        URI uri = new URI(url, false);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod();
        method.setURI(uri);
        client.executeMethod(method);

        response.setContentType(method.getResponseHeader("Content-Type").getValue());

        CopyUtils.copy(method.getResponseBodyAsStream(), response.getOutputStream());
    } catch (Exception e) {
        throw new ServletException("Unable to connect to caBIO", e);
    }

    return null;
}

From source file:ie.pars.nlp.sketchengine.interactions.SKEInteractionsBase.java

/**
 * Execute the query and return the results a json Object produced by SKE
 *
 * @param client//from w ww. j av  a2 s.com
 * @param query
 * @return
 * @throws URIException
 * @throws IOException
 */
JSONObject getHTTP(HttpClient client, String query) throws URIException, IOException {
    GetMethod getURI = new GetMethod(new URI(query, true).toString());
    client.executeMethod(getURI);
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getURI.getResponseBodyAsStream()));
    String line;
    StringBuilder k = new StringBuilder();

    while ((line = bufferedReader.readLine()) != null) {

        //  System.out.println(line);
        k.append(line).append("\n");
    }

    JSONObject json = new JSONObject(k.toString());

    return json;
}

From source file:com.braindrainpain.docker.httpsupport.HttpClientService.java

public void checkConnection(String url) {
    LOG.debug("Checking: '" + url + "'");
    try {/*www .  ja  v  a2s . co m*/
        URI uri = new URI(url, false);
        this.getMethod.setURI(uri);
        getMethod.setFollowRedirects(false);
        int status = httpClient.executeMethod(getMethod);
        if (status != HttpStatus.SC_OK) {
            LOG.error("Not ok from: '" + url + "'");
            LOG.error("status: " + status);
            throw new RuntimeException("Not ok from: '" + url + "'");
        }
    } catch (IOException e) {
        LOG.error("Error connecting to: '" + url + "'");
        throw new RuntimeException("Error connecting to: '" + url + "'");
    }
}

From source file:de.innovationgate.contentmanager.modules.LinkChecker.java

/**
 * checks if the given URL is reachable and returns the response code
 * redirects of type 301, 302, 303 and 307 are followed <code>getMaxRedirects()</code> times automatically 
 * @param uri the uri to check/*from  w w  w.  ja  v  a2 s.  c  o m*/
 * @return HTTP reponse code
 * @throws IOException 
 * @throws HttpException 
 * @throws IllegalStateException if max redirects has been reached
 */
public int check(String uri) throws HttpException, IOException {
    HttpClient client = WGFactory.getHttpClientFactory().createHttpClient();
    return innerCheck(client, new URI(uri, true), 0);
}