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

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

Introduction

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

Prototype

public abstract URI getURI() throws URIException;

Source Link

Usage

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverterTest.java

public void testGetTag() throws Exception {
    String uri = ((HTTPAddress) deliciousPort.getExtensibilityElements().get(0)).getLocationURI();
    String expectedUri = uri + "/tag/java";
    Element msgEl;//  w  w w .j  a v a2s  .c  o  m
    {
        Document odeMsg = DOMUtils.newDocument();
        msgEl = odeMsg.createElementNS(null, "message");
        Element partEl = odeMsg.createElementNS(null, "TagPart");
        partEl.setTextContent("java");
        odeMsg.appendChild(msgEl);
        msgEl.appendChild(partEl);
    }

    MockMessageExchange odeMex = new MockMessageExchange();
    odeMex.op = deliciousBinding.getBindingOperation("getTag", null, null).getOperation();
    odeMex.req = new MockMessage(msgEl);
    odeMex.epr = new MockEPR(uri);
    HttpMethod httpMethod = deliciousBuilder.createHttpRequest(odeMex, new DefaultHttpParams());

    assertTrue("GET".equalsIgnoreCase(httpMethod.getName()));
    assertTrue(expectedUri.equalsIgnoreCase(httpMethod.getURI().toString()));
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverterTest.java

public void testHello() throws Exception {
    String uri = ((HTTPAddress) dummyPort.getExtensibilityElements().get(0)).getLocationURI();
    String expectedUri = uri + "/" + "DummyService/hello";
    Element msgEl, helloEl;//  w w  w .  j  a  va2s  .c  o  m
    {
        Document odeMsg = DOMUtils.newDocument();
        msgEl = odeMsg.createElementNS(null, "message");
        Element partEl = odeMsg.createElementNS(null, "parameters");
        odeMsg.appendChild(msgEl);
        msgEl.appendChild(partEl);
        helloEl = odeMsg.createElementNS(null, "hello");
        helloEl.setTextContent("This is a test. How is it going so far?");
        partEl.appendChild(helloEl);
    }

    MockMessageExchange odeMex = new MockMessageExchange();
    odeMex.op = dummyBinding.getBindingOperation("hello", null, null).getOperation();
    odeMex.req = new MockMessage(msgEl);
    odeMex.epr = new MockEPR(uri);
    HttpMethod httpMethod = dummyBuilder.createHttpRequest(odeMex, new DefaultHttpParams());
    assertTrue("POST".equalsIgnoreCase(httpMethod.getName()));
    assertEquals("Generated URI does not match", expectedUri, httpMethod.getURI().toString());

    String b = ((StringRequestEntity) ((PostMethod) httpMethod).getRequestEntity()).getContent();
    assertEquals("Invalid body in generated http query", DOMUtils.domToString(helloEl), b);
}

From source file:org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.java

public NamedList<Object> request(final SolrRequest request, ResponseParser processor)
        throws SolrServerException, IOException {
    HttpMethod method = null;
    InputStream is = null;//from  ww w  .  j a v a2  s  .c om
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = "/select";
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = _parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original params
    ModifiableSolrParams wparams = new ModifiableSolrParams();
    wparams.set(CommonParams.WT, parser.getWriterType());
    wparams.set(CommonParams.VERSION, parser.getVersion());
    if (params == null) {
        params = wparams;
    } else {
        params = new DefaultSolrParams(wparams, params);
    }

    if (_invariantParams != null) {
        params = new DefaultSolrParams(_invariantParams, params);
    }

    int tries = _maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = _baseURL + path;
                    boolean isMultipart = (streams != null && streams.size() > 1);

                    if (streams == null || isMultipart) {
                        PostMethod post = new PostMethod(url);
                        post.getParams().setContentCharset("UTF-8");
                        if (!this.useMultiPartPost && !isMultipart) {
                            post.addRequestHeader("Content-Type",
                                    "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<Part> parts = new LinkedList<Part>();
                        Iterator<String> iter = params.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = params.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (this.useMultiPartPost || isMultipart) {
                                        parts.add(new StringPart(p, v, "UTF-8"));
                                    } else {
                                        post.addParameter(p, v);
                                    }
                                }
                            }
                        }

                        if (isMultipart) {
                            int i = 0;
                            for (ContentStream content : streams) {
                                final ContentStream c = content;

                                String charSet = null;
                                PartSource source = new PartSource() {
                                    public long getLength() {
                                        return c.getSize();
                                    }

                                    public String getFileName() {
                                        return c.getName();
                                    }

                                    public InputStream createInputStream() throws IOException {
                                        return c.getStream();
                                    }
                                };

                                parts.add(new FilePart(c.getName(), source, c.getContentType(), charSet));
                            }
                        }
                        if (parts.size() > 0) {
                            post.setRequestEntity(new MultipartRequestEntity(
                                    parts.toArray(new Part[parts.size()]), post.getParams()));
                        }

                        method = post;
                    }
                    // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = ClientUtils.toQueryString(params, false);
                        PostMethod post = new PostMethod(url + pstr);
                        //              post.setRequestHeader("connection", "close");

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setRequestEntity(new RequestEntity() {
                                public long getContentLength() {
                                    return -1;
                                }

                                public String getContentType() {
                                    return contentStream[0].getContentType();
                                }

                                public boolean isRepeatable() {
                                    return false;
                                }

                                public void writeRequest(OutputStream outputStream) throws IOException {
                                    ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream);
                                }
                            });

                        } else {
                            is = contentStream[0].getStream();
                            post.setRequestEntity(
                                    new InputStreamRequestEntity(is, contentStream[0].getContentType()));
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                // This is generally safe to retry on
                method.releaseConnection();
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if ((tries < 1)) {
                    throw r;
                }
                //log.warn( "Caught: " + r + ". Retrying..." );
            }
        }
    } catch (IOException ex) {
        log.error("####request####", ex);
        throw new SolrServerException("error reading streams", ex);
    }

    method.setFollowRedirects(_followRedirects);
    method.addRequestHeader("User-Agent", AGENT);
    if (_allowCompression) {
        method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate"));
    }
    //    method.setRequestHeader("connection", "close");

    try {
        // Execute the method.
        //System.out.println( "EXECUTE:"+method.getURI() );

        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            StringBuilder msg = new StringBuilder();
            msg.append(method.getStatusLine().getReasonPhrase());
            msg.append("\n\n");
            msg.append(method.getStatusText());
            msg.append("\n\n");
            msg.append("request: " + method.getURI());
            throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8"));
        }

        // Read the contents
        String charset = "UTF-8";
        if (method instanceof HttpMethodBase) {
            charset = ((HttpMethodBase) method).getResponseCharSet();
        }
        InputStream respBody = method.getResponseBodyAsStream();
        // Jakarta Commons HTTPClient doesn't handle any
        // compression natively.  Handle gzip or deflate
        // here if applicable.
        if (_allowCompression) {
            Header contentEncodingHeader = method.getResponseHeader("Content-Encoding");
            if (contentEncodingHeader != null) {
                String contentEncoding = contentEncodingHeader.getValue();
                if (contentEncoding.contains("gzip")) {
                    //log.debug( "wrapping response in GZIPInputStream" );
                    respBody = new GZIPInputStream(respBody);
                } else if (contentEncoding.contains("deflate")) {
                    //log.debug( "wrapping response in InflaterInputStream" );
                    respBody = new InflaterInputStream(respBody);
                }
            } else {
                Header contentTypeHeader = method.getResponseHeader("Content-Type");
                if (contentTypeHeader != null) {
                    String contentType = contentTypeHeader.getValue();
                    if (contentType != null) {
                        if (contentType.startsWith("application/x-gzip-compressed")) {
                            //log.debug( "wrapping response in GZIPInputStream" );
                            respBody = new GZIPInputStream(respBody);
                        } else if (contentType.startsWith("application/x-deflate")) {
                            //log.debug( "wrapping response in InflaterInputStream" );
                            respBody = new InflaterInputStream(respBody);
                        }
                    }
                }
            }
        }
        return processor.processResponse(respBody, charset);
    } catch (HttpException e) {
        throw new SolrServerException(e);
    } catch (IOException e) {
        throw new SolrServerException(e);
    } finally {
        method.releaseConnection();
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.apache.tapestry5.cdi.test.InjectTest.java

/**
 * Connect to an url thanks to an HttpClient if provided and return the response content as a String 
 * Use same HttpClient to keep same HttpSession through multiple getResponse method calls  
 * @param url an url to connect to/*ww  w .  ja va2  s  .c o m*/
 * @param client an HTTPClient to use to serve the url
 * @return the response as a String
 */
private String getResponse(URL url, HttpClient client) {
    HttpClient newClient = client == null ? new HttpClient() : client;
    HttpMethod get = new GetMethod(url.toString());
    String output = null;
    int out = 200;
    try {
        out = newClient.executeMethod(get);
        if (out != 200) {
            throw new RuntimeException("get " + get.getURI() + " returned " + out);
        }
        output = get.getResponseBodyAsString();

    } catch (HttpException e) {
        e.printStackTrace();
        throw new RuntimeException("get " + url + " returned " + out);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("get " + url + " returned " + out);
    } finally {
        get.releaseConnection();
    }
    return output;
}

From source file:org.apache.wookie.proxy.ProxyClient.java

private String executeMethod(HttpMethod method, Configuration properties)
        throws Exception, AuthenticationException {
    // Execute the method.
    try {// ww  w  . j ava  2 s . co  m
        HttpClient client = new HttpClient();

        // set the clients proxy values if needed
        ConnectionsPrefsManager.setProxySettings(client, properties);

        if (fUseProxyAuthentication) {
            if (fBase64Auth != null) {
                method.setRequestHeader("Authorization", fBase64Auth);
            } else {
                List<String> authPrefs = new ArrayList<String>(2);
                authPrefs.add(AuthPolicy.DIGEST);
                authPrefs.add(AuthPolicy.BASIC);
                client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
                // send the basic authentication response even before the server gives an unauthorized response
                client.getParams().setAuthenticationPreemptive(true);
                // Pass our credentials to HttpClient
                client.getState().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                        new UsernamePasswordCredentials(fProxyUsername, fProxyPassword));
            }
        }

        // Add user language to http request in order to notify server of user's language
        Locale locale = Locale.getDefault();

        method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$
        method.removeRequestHeader("Content-Type");
        //method.setRequestHeader("Content-Type","application/json");
        //method.setRequestHeader("Referer", "");
        //method.removeRequestHeader("Referer");
        method.setRequestHeader("Accept", "*/*");

        int statusCode = client.executeMethod(method);

        //System.out.println("response="+method.getResponseBodyAsString());
        //System.out.println("method="+method.toString());
        //System.out.println("response="+method.getResponseBodyAsStream());

        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            Header hType = method.getResponseHeader("Content-Type");
            if (hType != null) {
                fContentType = hType.getValue();
            }
            // for now we are only expecting Strings
            //return method.getResponseBodyAsString();
            return readFully(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED
                || statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationException("Authentication failed:" + method.getStatusLine() + ' '
                    + method.getURI() + ' ' + method.getStatusText());
        } else {
            throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$
                    + method.getStatusText());
        }
    } catch (IOException e) {
        throw e;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.apache.wookie.util.gadgets.GadgetUtils.java

/**
 * Call a remote service//from  www . ja  v a  2  s .c  o  m
 * @param method the method to invoke
 * @return the response from the remote service
 * @throws Exception
 */
private static String executeMethod(HttpMethod method) throws Exception {
    // Execute the method.
    System.out.println("executeMethod() start");
    try {
        HttpClient client = new HttpClient();

        // Add user language to http request in order to notify server of user's language
        Locale locale = Locale.getDefault();

        method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$ 
        int statusCode = client.executeMethod(method);
        System.out.println("HTTP client returned status:" + statusCode);
        if (statusCode == HttpStatus.SC_OK) {
            // for now we are only expecting Strings               
            return method.getResponseBodyAsString();
        } else {
            throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$
                    + method.getStatusText() + method.getResponseBodyAsString());
        }
    } catch (IOException e) {
        System.out.println("CaughtIOException");
        throw new Exception("ERROR_CONNECT", e);
    } finally {
        // Release the connection.
        System.out.println("executeMethod() end");
        method.releaseConnection();
    }
}

From source file:org.artifactory.cli.rest.RestClient.java

/**
 * Writes the response stream to the selected outputs
 *
 * @param method      The method that was executed
 * @param printStream True if should print response stream to system.out
 * @return byte[] Response/*from www. jav a2s. c o m*/
 * @throws IOException
 */
private static byte[] analyzeResponse(HttpMethod method, boolean printStream) throws IOException {
    InputStream is = method.getResponseBodyAsStream();
    if (is == null) {
        return null;
    }
    byte[] buffer = new byte[1024];
    int r;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream os = baos;
        if (printStream) {
            os = new TeeOutputStream(baos, System.out);
        }
        while ((r = is.read(buffer)) != -1) {
            os.write(buffer, 0, r);
        }
        if (printStream) {
            System.out.println("");
        }
        return baos.toByteArray();
    } catch (SocketTimeoutException e) {
        CliLog.error("Communication with the server has timed out: " + e.getMessage());
        CliLog.error("ATTENTION: The command on the server may still be running!");
        String url = method.getURI().toString();
        int apiPos = url.indexOf("/api");
        String logsUrl;
        if (apiPos != -1) {
            logsUrl = url.substring(0, apiPos) + "/webapp/systemlogs.html";
        } else {
            logsUrl = "http://" + method.getURI().getHost() + "/artifactory/webapp/systemlogs.html";
        }
        CliLog.error("Please check the server logs " + logsUrl + " before re-running the command.");
        return null;
    }
}

From source file:org.cancergrid.ws.util.HttpContentReader.java

public static String getHttpContent(String httpUrl, String query, Method method) {
    LOG.debug("getHttpContent(httpUrl): " + httpUrl);
    LOG.debug("getHttpContent(query): " + query);
    LOG.debug("getHttpContent(method): " + method);

    HttpMethod httpMethod = null;
    if (httpUrl.contains("&amp;")) {
        httpUrl = httpUrl.replace("&amp;", "&");
    }/*ww w  .j a va 2  s .co  m*/

    if (query != null && query.length() > 0 && query.startsWith("?") && query.contains("&amp;")) {
        query = query.replace("&amp;", "&");
    }

    try {
        //LOG.debug("Querying: " + httpUrl);
        if (method == Method.GET) {
            httpMethod = new GetMethod(httpUrl);
            if (query != null && query.length() > 0) {
                httpMethod.setQueryString(query);
            }
        } else if (method == Method.POST) {
            httpMethod = new PostMethod(httpUrl);
            if (query != null && query.length() > 0) {
                RequestEntity entity = new StringRequestEntity(query, "text/xml", "UTF-8");
                ((PostMethod) httpMethod).setRequestEntity(entity);
            }
        }

        httpMethod.setFollowRedirects(true);

        httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        Protocol.registerProtocol("https", new Protocol("https",
                new org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(), 443));
        HttpClient client = new HttpClient();
        int statusCode = client.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + httpMethod.getStatusLine());
            LOG.error("Error querying: " + httpMethod.getURI().toString());
            throw new Exception("Method failed: " + httpMethod.getStatusLine());
        }

        byte[] responseBody = httpMethod.getResponseBody();
        return new String(responseBody, "UTF-8");
    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
    } catch (Exception e) {
        LOG.error(e.getMessage());
    } finally {
        httpMethod.releaseConnection();
    }
    return null;
}

From source file:org.chiba.xml.xforms.connector.http.AbstractHTTPConnector.java

protected void execute(HttpMethod httpMethod) throws Exception {
    //      (new HttpClient()).executeMethod(httpMethod);
    HttpClient client = new HttpClient();

    if (submissionMap != null) {
        String sessionid = submissionMap.get(ChibaAdapter.SESSION_ID).toString();
        if (sessionid != null) {
            HttpState state = client.getState();
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
            state.addCookie(new Cookie(httpMethod.getURI().getHost(), "JSESSIONID", sessionid,
                    httpMethod.getPath(), null, false));
            client.setState(state);/*from w ww.jav  a  2s. c om*/
        }
    }

    client.executeMethod(httpMethod);

    if (httpMethod.getStatusCode() >= 300) {
        throw new XFormsException(
                "HTTP status " + httpMethod.getStatusCode() + ": " + httpMethod.getStatusText());
    }
    this.handleHttpMethod(httpMethod);
}

From source file:org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection.java

private void doRequest(Returned out, RequestMethod method_type, String uri, RequestDataSource src,
        CSPRequestCredentials creds, CSPRequestCache cache) throws ConnectionException {
    InputStream body_data = null;
    if (src != null) {
        body_data = src.getStream();/*www .j  av a2 s  .  co  m*/
    }
    try {
        HttpMethod method = createMethod(method_type, uri, body_data);
        if (body_data != null) {
            method.setRequestHeader("Content-Type", src.getMIMEType());
            // XXX Not sure if or when this ever actually writes to stderr?
            body_data = new TeeInputStream(body_data, System.err);
        }
        try {
            HttpClient client = makeClient(creds, cache);

            String requestContext = null;
            if (perflog.isDebugEnabled()) {
                // TODO add more context, e.g. session id?
                requestContext = "HttpClient@" + Integer.toHexString(client.hashCode());
                requestContext += "/CSPRequestCache@" + Integer.toHexString(cache.hashCode()) + ",";
                //String queryString = method.getQueryString();
                perflog.debug(System.currentTimeMillis() + ",\"" + Thread.currentThread().getName()
                        + "\",app,svc," + requestContext + method.getName() + " " + method.getURI()
                //+ (queryString!=null ? queryString : "")
                );
            }

            int response = client.executeMethod(method);

            if (perflog.isDebugEnabled()) {
                perflog.debug(System.currentTimeMillis() + ",\"" + Thread.currentThread().getName()
                        + "\",svc,app," + requestContext + "HttpClient.executeMethod done");
            }

            out.setResponse(method, response);
        } catch (ConnectionException e) {
            throw new ConnectionException(e.getMessage(), e.status, base_url + "/" + uri, e);
        } catch (Exception e) {
            throw new ConnectionException(e.getMessage(), 0, base_url + "/" + uri, e);
        } finally {
            method.releaseConnection();

            if (log.isWarnEnabled()) {
                if (manager.getConnectionsInPool() >= MAX_SERVICES_CONNECTIONS) {
                    log.warn("reached max services connection limit of " + MAX_SERVICES_CONNECTIONS);

                    // Delete closed connections from the pool, so that the warning will cease
                    // once a connection becomes available.
                    manager.deleteClosedConnections();
                }
            }
        }
    } finally {
        closeStream(body_data);
    }
}