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:net.oauth.client.httpclient3.HttpMethodResponse.java

/**
 * Construct an OAuthMessage from the HTTP response, including parameters
 * from OAuth WWW-Authenticate headers and the body. The header parameters
 * come first, followed by the ones from the response body.
 *//*  ww w . ja v  a 2 s  .c  o  m*/
public HttpMethodResponse(HttpMethod method, byte[] requestBody, String requestEncoding) throws IOException {
    super(method.getName(), new URL(method.getURI().toString()));
    this.method = method;
    this.requestBody = requestBody;
    this.requestEncoding = requestEncoding;
    this.headers.addAll(getHeaders());
}

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, Server server,
        String uri, AuthToken authToken) throws IOException, ServiceException {
    if (server == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "cannot find remote server");
        return;/*w  ww.  ja  v  a  2s  .  co  m*/
    }
    HttpMethod method;
    String url = getProxyUrl(req, server, uri);
    mLog.debug("Proxy URL = %s", url);
    if (req.getMethod().equalsIgnoreCase("GET")) {
        method = new GetMethod(url.toString());
    } else if (req.getMethod().equalsIgnoreCase("POST") || req.getMethod().equalsIgnoreCase("PUT")) {
        PostMethod post = new PostMethod(url.toString());
        post.setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
        method = post;
    } else {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "cannot proxy method: " + req.getMethod());
        return;
    }
    HttpState state = new HttpState();
    String hostname = method.getURI().getHost();
    if (authToken != null) {
        authToken.encode(state, false, hostname);
    }
    try {
        proxyServletRequest(req, resp, method, state);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.zimbra.cs.service.UserServlet.java

private static Pair<Header[], HttpMethod> doHttpOp(ZAuthToken authToken, HttpMethod method)
        throws ServiceException {
    // create an HTTP client with the same cookies
    String url = "";
    String hostname = "";
    try {/*  w  ww . j av  a2s  .c  o  m*/
        url = method.getURI().toString();
        hostname = method.getURI().getHost();
    } catch (IOException e) {
        log.warn("can't parse target URI", e);
    }

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    Map<String, String> cookieMap = authToken.cookieMap(false);
    if (cookieMap != null) {
        HttpState state = new HttpState();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            state.addCookie(new org.apache.commons.httpclient.Cookie(hostname, ck.getKey(), ck.getValue(), "/",
                    null, false));
        }
        client.setState(state);
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }

    if (method instanceof PutMethod) {
        long contentLength = ((PutMethod) method).getRequestEntity().getContentLength();
        if (contentLength > 0) {
            int timeEstimate = Math.max(10000, (int) (contentLength / 100)); // 100kbps in millis
            // cannot set connection time using our ZimbrahttpConnectionManager,
            // see comments in ZimbrahttpConnectionManager.
            // actually, length of the content to Put should not be a factor for
            // establishing a connection, only read time out matter, which we set
            // client.getHttpConnectionManager().getParams().setConnectionTimeout(timeEstimate);

            method.getParams().setSoTimeout(timeEstimate);
        }
    }

    try {
        int statusCode = HttpClientUtil.executeMethod(client, method);
        if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_FORBIDDEN)
            throw MailServiceException.NO_SUCH_ITEM(-1);
        else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NO_CONTENT)
            throw ServiceException.RESOURCE_UNREACHABLE(method.getStatusText(), null,
                    new ServiceException.InternalArgument(HTTP_URL, url, ServiceException.Argument.Type.STR),
                    new ServiceException.InternalArgument(HTTP_STATUS_CODE, statusCode,
                            ServiceException.Argument.Type.NUM));

        List<Header> headers = new ArrayList<Header>(Arrays.asList(method.getResponseHeaders()));
        headers.add(new Header("X-Zimbra-Http-Status", "" + statusCode));
        return new Pair<Header[], HttpMethod>(headers.toArray(new Header[0]), method);
    } catch (HttpException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("HttpException while fetching " + url, e);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("IOException while fetching " + url, e);
    }
}

From source file:com.knowledgebooks.info_spiders.DBpediaLookupClient.java

public DBpediaLookupClient(String query) throws Exception {
    this.query = query;
    //System.out.println("\n query: " + query);
    HttpClient client = new HttpClient();

    String query2 = query.replaceAll(" ", "+"); // URLEncoder.encode(query, "utf-8");
    //System.out.println("\n query2: " + query2);
    HttpMethod method = new GetMethod(
            "http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=" + query2);
    try {// www. ja va 2s  .  c o m
        System.out.println("\n method: " + method.getURI());
        client.executeMethod(method);
        System.out.println(method);
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.err.println("Http error connecting to lookup.dbpedia.org");
    } catch (IOException ioe) {
        System.err.println("Unable to connect to lookup.dbpedia.org");
    }
    method.releaseConnection();
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.interceptor.HttpMethodBaseExecuteMethodInterceptor.java

private String getHost(HttpMethod httpMethod, HttpConnection httpConnection) {
    try {//from   w w w .  j a va 2 s. c o m
        final URI uri = httpMethod.getURI();
        // if uri have schema
        if (uri.isAbsoluteURI()) {
            return HttpClient3RequestWrapper.getEndpoint(uri.getHost(), uri.getPort());
        }
        if (httpConnection != null) {
            final String host = httpConnection.getHost();
            final int port = HttpClient3RequestWrapper.getPort(httpConnection);
            return HttpClient3RequestWrapper.getEndpoint(host, port);
        }
    } catch (Exception e) {
        if (isDebug) {
            logger.debug("Failed to get host. httpMethod={}", httpMethod, e);
        }
    }
    return null;
}

From source file:at.ac.tuwien.auto.sewoa.http.HttpRetrieverImpl.java

private byte[] send(HttpClient httpClient, HttpMethod method) {
    try {//from   w w w. j  a v a2s  .  c o m
        int httpResult = httpClient.executeMethod(method);
        if (httpResult != HttpURLConnection.HTTP_OK) {
            LOGGER.warn("cannot post data to url {} -> result: {}.", method.getURI().toString(), httpResult);
            ByteStreams.toByteArray(method.getResponseBodyAsStream());
            throw new IllegalStateException("error code");
        } else {
            return ByteStreams.toByteArray(method.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        LOGGER.warn("cannot post http data to url {} due to {}.", method.toString(), e.getMessage());
        throw new IllegalStateException("could not post data");
    }
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.interceptor.ExecuteInterceptor.java

private String getHost(HttpMethod httpMethod) {
    try {//from   w  ww.j  a v  a 2 s  . co  m
        return httpMethod.getURI().getHost();
    } catch (URIException e) {
        logger.error("Fail get URI", e);
    }

    return null;
}

From source file:com.sun.syndication.feed.weather.WeatherGateway.java

protected WeatherChannel doQuery(String locationID, long allowedAge, NameValuePair[] query) throws IOException {
    HttpClient client = new HttpClient();

    HttpMethod method = new GetMethod(weatherServer + locationID);
    method.setQueryString(query);/*from ww w. j a v  a 2  s .  c  om*/

    URI uri = method.getURI();
    LOG.debug("Performing query with URI:  " + uri);

    WeatherChannel channel = new WeatherChannel();

    if (weatherCache.containsKey(uri)) {
        WeatherCacheEntry entry = (WeatherCacheEntry) weatherCache.get(uri);

        long lastUpdated = entry.getLastUpdated().getTimeInMillis();
        LOG.debug("Cache entry last updated:  " + lastUpdated);
        long now = new GregorianCalendar().getTimeInMillis();
        LOG.debug("Cache entry current time:  " + now);
        long diffMillis = now - lastUpdated;
        LOG.debug("Cache entry time difference is:  " + diffMillis);

        if (diffMillis < allowedAge) {
            channel = entry.getChannel();
            LOG.debug("Returning channel from cache.");
            return channel;
        }
    }

    int statusCode = -1;

    for (int attempt = 0; statusCode == -1 && attempt < 3; attempt++) {
        try {
            statusCode = client.executeMethod(method);
        } catch (HttpRecoverableException e) {
            LOG.warn("Retrying after recoverable exception:  " + e.getMessage());
        } catch (IOException e) {
            LOG.error("Failed to download file:  " + e.getMessage());
        }
    }

    if (statusCode == -1) {
        LOG.error("Failed to recover from exception.");
        throw new IOException();
    }

    channel = buildWeather(method);
    WeatherCacheEntry entry = new WeatherCacheEntry(channel);
    weatherCache.put(uri, entry);
    LOG.debug("Returning channel from network.");
    return channel;
}

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

/**
 * Tries to execute the {@link HttpMethod} and captures the {@link ValidatorException exception} which is thrown if user connects
 * to an HTTPS server with a non-trusted (probably, self-signed) SSL certificate. In which case proposes to cancel the connection
 * or to proceed without certificate check.
 *
 * @param methodCreator a function to create the HttpMethod. This is required instead of just {@link HttpMethod} instance, because the
 *                      implementation requires the HttpMethod to be recreated in certain circumstances.
 * @return the HttpMethod instance which was actually executed
 *         and which can be {@link HttpMethod#getResponseBodyAsString() asked for the response}.
 * @throws IOException in case of other errors or if user declines the proposal of non-trusted connection.
 *///from   w w w  .ja  v a2  s.co m
@NotNull
public HttpMethod executeSelfSignedCertificateAwareRequest(@NotNull HttpClient client, @NotNull String uri,
        @NotNull ThrowableConvertor<String, HttpMethod, IOException> methodCreator) throws IOException {
    HttpMethod method = methodCreator.convert(uri);
    try {
        client.executeMethod(method);
        return method;
    } catch (IOException e) {
        HttpMethod m = handleCertificateExceptionAndRetry(e, method.getURI().getHost(), client, method.getURI(),
                methodCreator);
        if (m == null) {
            throw e;
        }
        return m;
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClientTest.java

private boolean pathMatches(HttpMethod method, String path) throws URIException {
    return method.getURI().getPath().equals(path);
}