Example usage for org.apache.commons.httpclient.methods GetMethod GetMethod

List of usage examples for org.apache.commons.httpclient.methods GetMethod GetMethod

Introduction

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

Prototype

public GetMethod(String uri) 

Source Link

Usage

From source file:net.sf.ehcache.constructs.web.filter.CachingFilterTest.java

/**
 * HEAD methods return an empty response body. If a HEAD request populates
 * a cache and then a GET follorws, a blank page will result.
 * This test ensures that the SimplePageCachingFilter implements calculateKey
 * properly to avoid this problem./*from  ww  w. j  a  v a 2 s. co  m*/
 */
public void testHeadThenGetOnCachedPage() throws Exception {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new HeadMethod(buildUrl(cachedPageUrl));
    int responseCode = httpClient.executeMethod(httpMethod);
    //httpclient follows redirects, so gets the home page.
    assertEquals(HttpURLConnection.HTTP_OK, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertNull(responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));

    httpMethod = new GetMethod(buildUrl(cachedPageUrl));
    responseCode = httpClient.executeMethod(httpMethod);
    responseBody = httpMethod.getResponseBodyAsString();
    assertNotNull(responseBody);

}

From source file:at.ait.dme.yuma.server.map.KMLConverterServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Params: URL of the base map into which KML shall be transformed, URL of the KML  
    String europeanaUri = request.getParameter("europeanaUri");
    String mapUrl = request.getParameter("map");
    String kmlUrl = request.getParameter("kml");

    if ((mapUrl != null) && (kmlUrl != null)) {
        // Get KML source file via HTTP
        GetMethod kmlRequest = new GetMethod(kmlUrl);
        int responseCode = new HttpClient().executeMethod(kmlRequest);
        if (responseCode == 200) {
            try {
                // Parse KML DOM
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document kml = builder.parse(kmlRequest.getResponseBodyAsStream());

                // Instantiate Interpolator
                ControlPointManager cpm = new ControlPointManager(request, response, europeanaUri, mapUrl);
                AffineTransformation ip = new AffineTransformation(cpm.getControlPoints());

                // Convert coordinates in DOM
                kml = convert(kml, ip);/*  ww  w. ja  v  a 2s .c om*/

                // Serialize KML result DOM and return
                Transformer tf = TransformerFactory.newInstance().newTransformer();
                Source source = new DOMSource(kml);
                Result result = new StreamResult(response.getOutputStream());
                tf.transform(source, result);
            } catch (Exception e) {
                response.sendError(500, e.getMessage());
                return;
            }
        } else {
            response.sendError(500, "KML not found. (Server returned error " + responseCode + ")");
            return;
        }

        response.setContentType("application/vnd.google-earth.kml+xml");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("done");
    } else {
        response.sendError(404);
    }
}

From source file:com.wandisco.s3hdfs.rewrite.redirect.Redirect.java

HttpMethod getHttpMethod(String scheme, String host, int port, String op, String userName, String uri,
        HTTP_METHOD method) {//from www  . ja v  a 2 s .  c  o  m

    if (!uri.startsWith(WEBHDFS_PREFIX))
        uri = ADD_WEBHDFS(uri);

    String url = scheme + "://" + host + ":" + port + uri + "?user.name=" + userName + "&op=" + op;
    switch (method) {
    case GET:
        return new GetMethod(url);
    case PUT:
        return new PutMethod(url);
    case POST:
        return new PostMethod(url);
    case DELETE:
        return new DeleteMethod(url);
    case HEAD:
        return new HeadMethod(url);
    default:
        return null;
    }
}

From source file:eu.learnpad.rest.utils.internal.DefaultRestUtils.java

@Override
public boolean isPage(String spaceName, String pageName) {
    HttpClient httpClient = getClient();

    String uri = REST_URI + "/wikis/xwiki/spaces/" + spaceName + "/pages/" + pageName;
    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader("Accept", "application/xml");
    getMethod.addRequestHeader("Accept-Ranges", "bytes");
    try {/* w w w .  j a v a  2 s  . c  om*/
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode == 200) {
            return true;
        }
    } catch (HttpException e) {
        logger.error("Unable to process the GET request on page '" + spaceName + "." + pageName + "'.", e);
        return false;
    } catch (IOException e) {
        logger.error("Unable to GET the page '" + spaceName + "." + pageName + "'.", e);
        return false;
    }
    return false;
}

From source file:com.owncloud.android.lib.resources.users.GetRemoteUserAvatarOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    GetMethod get = null;//from w w  w .ja  va  2 s.  c om
    InputStream inputStream = null;

    try {
        String uri = client.getBaseUri() + NON_OFFICIAL_AVATAR_PATH + client.getCredentials().getUsername()
                + "/" + mDimension;
        ;
        Log_OC.d(TAG, "avatar URI: " + uri);
        get = new GetMethod(uri);
        if (mCurrentEtag != null && mCurrentEtag.length() > 0) {
            get.addRequestHeader(IF_NONE_MATCH_HEADER, "\"" + mCurrentEtag + "\"");
        }
        //get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        int status = client.executeMethod(get);
        if (isSuccess(status)) {

            // find out size of file to read
            int totalToTransfer = 0;
            Header contentLength = get.getResponseHeader("Content-Length");
            if (contentLength != null && contentLength.getValue().length() > 0) {
                totalToTransfer = Integer.parseInt(contentLength.getValue());
            }

            // find out MIME-type!
            String mimeType;
            Header contentType = get.getResponseHeader("Content-Type");
            if (contentType == null || !contentType.getValue().startsWith("image")) {
                Log_OC.e(TAG, "Not an image, failing with no avatar");
                result = new RemoteOperationResult(RemoteOperationResult.ResultCode.FILE_NOT_FOUND);
                return result;
            }
            mimeType = contentType.getValue();

            /// download will be performed to a buffer
            inputStream = get.getResponseBodyAsStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(totalToTransfer);

            long transferred = 0;
            byte[] bytes = new byte[4096];
            int readResult = 0;
            while ((readResult = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, readResult);
                transferred += readResult;
            }
            // TODO check total bytes transferred?

            // find out etag
            String etag = WebdavUtils.getEtagFromResponse(get);
            if (etag.length() == 0) {
                Log_OC.w(TAG, "Could not read Etag from avatar");
            }

            // Result
            result = new RemoteOperationResult(true, status, get.getResponseHeaders());
            ResultData resultData = new ResultData(bos.toByteArray(), mimeType, etag);
            ArrayList<Object> data = new ArrayList<Object>();
            data.add(resultData);
            result.setData(data);

        } else {
            client.exhaustResponse(get.getResponseBodyAsStream());
            result = new RemoteOperationResult(false, status, get.getResponseHeaders());
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while getting OC user avatar", e);

    } finally {
        if (get != null) {
            if (inputStream != null) {
                client.exhaustResponse(inputStream);
            }
            get.releaseConnection();
        }
    }

    return result;
}

From source file:com.sittinglittleduck.DirBuster.CheckForUpdates.java

public void run() {
    try {//from   w ww .  j av  a2s .  c  om
        GetMethod httpget = new GetMethod(updateURL);
        int responseCode = httpclient.executeMethod(httpget);

        if (responseCode == 200) {
            if (httpget.getResponseContentLength() > 0) {

                // get the http body
                String response = "";
                try (BufferedReader input = new BufferedReader(
                        new InputStreamReader(httpget.getResponseBodyAsStream()))) {
                    String line;

                    StringBuffer buf = new StringBuffer();
                    while ((line = input.readLine()) != null) {
                        buf.append("\r\n" + line);
                    }
                    response = buf.toString();
                }

                Matcher versionMatcher = VERSION_PATTERN.matcher(response);
                if (versionMatcher.find()) {
                    String latestversion = versionMatcher.group(1);
                    if (latestversion.equalsIgnoreCase("Running - latest")) {
                        showAlreadyLatestVersionMessage();
                    } else {
                        Matcher changelogMatcher = CHANGELOG_PATTERN.matcher(response);
                        if (changelogMatcher.find()) {
                            String changelog = changelogMatcher.group(1);

                            if (!manager.isHeadLessMode()) {
                                if (showUpdateToLatestVersionConfirmDialog(latestversion,
                                        changelog) == JOptionPane.OK_OPTION) {
                                    BrowserLauncher launcher;
                                    try {
                                        launcher = new BrowserLauncher(null);
                                        launcher.openURLinBrowser(DIRBUSTER_SOURCEFORGE_URL);
                                    } catch (BrowserLaunchingInitializingException
                                            | UnsupportedOperatingSystemException ex) {
                                        showErrorMessage(BROWSER_ERROR_MESSAGE + ex.getMessage());
                                    }
                                }
                            } else {
                                printUpdateMessageOnConsole(latestversion);
                            }
                        } else {
                            showErrorMessage(CHANGELOG_ERROR_MESSAGE);
                        }

                    }
                } else {
                    showErrorMessage(VERSION_ERROR_MESSAGE);
                }

            } else {
                showErrorMessage(OTHER_ERROR_MESSAGE);
            }

        } else {
            showErrorMessage(SERVER_ERROR_MESSAGE);
        }
    } catch (IOException ex) {
        showErrorMessage(DEFAULT_ERROR_MESSAGE + ex.getMessage());
    }
}

From source file:com.inbravo.scribe.rest.service.crm.zd.auth.basic.ZDBasicAuthManager.java

@Override
public final String getSessionId(final String userId, final String password, final String crmURL,
        final String crmProtocol, final String port) throws Exception {
    logger.debug("----Inside login userId: " + userId + " & password: " + password + " & crmURL: " + crmURL
            + " & crmProtocol: " + crmProtocol + " & crmPort: " + port);

    /* Validate protocol */
    if (crmProtocol == null || "".equalsIgnoreCase(crmProtocol)) {

        /* Send user error */
        throw new ScribeException(
                ScribeResponseCodes._1003 + "Invalid protocol to communicate with ZD: " + crmProtocol);
    }//from   w  w  w. jav a2s.  c  o  m

    /* Trick: Check all live users on CRM currently */
    final GetMethod getMethod = new GetMethod(crmProtocol + "://" + crmURL + "/users/current.xml");

    getMethod.addRequestHeader("Content-Type", "application/xml");
    final HttpClient httpclient = new HttpClient();

    /* Set credentials */
    httpclient.getState().setCredentials(new AuthScope(crmURL, this.validateCrmPort(port)),
            new UsernamePasswordCredentials(userId, password));

    try {
        int result = httpclient.executeMethod(getMethod);
        logger.debug("----Inside getSessionId response code: " + result + " & body: "
                + getMethod.getResponseBodyAsString());

        /* Check for authentication */
        if (result == HttpStatus.SC_UNAUTHORIZED) {
            logger.debug("----Inside getSessionId found unauthorized user");
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else {
            final String sessionId = getMethod.getResponseHeader("Set-Cookie").getValue();
            logger.debug("----Inside getSessionId sessionId: " + sessionId);
            return sessionId;
        }
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } finally {
        /* Release connection socket */
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
    }
}

From source file:exception.handler.authentication.UnhandledAuthenticationExceptionTest.java

@Test
public void authenticationException() throws HttpException, IOException {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(deploymentUrl + "/index.jsf");

    int status = client.executeMethod(method);
    assertEquals(SC_FORBIDDEN, status);/* ww  w.j a v a2  s. co  m*/
}

From source file:de.innovationgate.wgpublisher.cache.HttpCachePreloader.java

@Override
public String preloadCache(WGACore core, WGDatabase db) throws CachePreloadException {

    try {/*from  w w  w  .  j a v  a2s  .  com*/
        HttpClient client = WGFactory.getHttpClientFactory().createHttpClient();

        if (_credentials != null) {
            client.getState().setCredentials(AuthScope.ANY, _credentials);
            client.getParams().setAuthenticationPreemptive(true);
        }

        GetMethod method = new GetMethod(_url);

        if (_prepareTask != null) {
            _prepareTask.prepare(client, method);
        }

        int status = client.executeMethod(method);

        if (method.getStatusCode() != 200) {
            if (method.getStatusCode() == 503 || method.getStatusCode() == 504 || method.getStatusCode() == 507
                    || method.getStatusCode() == 509) {
                throw new CachePreloadException("HTTP Status Code is " + method.getStatusCode()
                        + ". Server either timed out or not ready. Will requeue.", false);
            } else {
                throw new CachePreloadException("HTTP Status Code is " + method.getStatusCode(), false);
            }
        }

        Reader reader;
        if (method.getResponseCharSet() != null) {
            reader = new InputStreamReader(method.getResponseBodyAsStream(), method.getResponseCharSet());
        } else {
            reader = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
        }

        String contents = WGUtils.readString(reader);
        return contents;
    } catch (Exception e) {
        throw new CachePreloadException("Exception preloading cache", e, false);
    }

}

From source file:com.twistbyte.affiliate.HttpUtility.java

/**
 * Do a get request to the given url and set the header values passed
 *
 * @param url/*from   ww w.  j  a v a 2s. co m*/
 * @param headerValues
 * @return
 */
public HttpResult doGet(String url, Map<String, String> headerValues) {

    String resp = "";

    logger.info("url : " + url);
    GetMethod method = new GetMethod(url);

    logger.info("Now use connection timeout: " + connectionTimeout);
    httpclient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectionTimeout);

    if (headerValues != null) {
        for (Map.Entry<String, String> entry : headerValues.entrySet()) {

            method.setRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResult serviceResult = new HttpResult();
    serviceResult.setSuccess(false);
    serviceResult.setHttpStatus(404);
    Reader reader = null;
    try {

        int result = httpclient.executeMethod(new HostConfiguration(), method, new HttpState());
        logger.info("http result : " + result);
        resp = method.getResponseBodyAsString();

        logger.info("response: " + resp);

        serviceResult.setHttpStatus(result);
        serviceResult.setBody(resp);
        serviceResult.setSuccess(200 == serviceResult.getHttpStatus());
    } catch (java.net.ConnectException ce) {
        logger.warn("ConnectException: " + ce.getMessage());
    } catch (IOException e) {
        logger.error("IOException sending request to " + url + " Reason:" + e.getMessage(), e);
    } finally {
        method.releaseConnection();
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {

            }
        }
    }

    return serviceResult;
}