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:com.owncloud.android.lib.resources.users.GetPrivateKeyOperation.java

/**
 * @param client Client object//from w  w w . ja va  2s  . com
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    GetMethod getMethod = null;
    RemoteOperationResult result;

    try {
        // remote request
        getMethod = new GetMethod(client.getBaseUri() + PUBLIC_KEY_URL + JSON_FORMAT);
        getMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

        int status = client.executeMethod(getMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        if (status == HttpStatus.SC_OK) {
            ServerResponse<PrivateKey> serverResponse = getServerResponse(getMethod,
                    new TypeToken<ServerResponse<PrivateKey>>() {
                    });

            result = new RemoteOperationResult(true, getMethod);
            ArrayList<Object> keys = new ArrayList<>();
            keys.add(serverResponse.getOcs().getData().getKey());
            result.setData(keys);
        } else {
            result = new RemoteOperationResult(false, getMethod);
            client.exhaustResponse(getMethod.getResponseBodyAsStream());
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Fetching of public key failed: " + result.getLogMessage(), result.getException());
    } finally {
        if (getMethod != null)
            getMethod.releaseConnection();
    }
    return result;
}

From source file:com.rometools.propono.blogclient.metaweblog.MetaWeblogResource.java

/**
 * Get media resource as input stream./*w  ww .  j  ava2  s . c  o m*/
 */
@Override
public InputStream getAsStream() throws BlogClientException {
    final HttpClient httpClient = new HttpClient();
    final GetMethod method = new GetMethod(permalink);
    try {
        httpClient.executeMethod(method);
    } catch (final Exception e) {
        throw new BlogClientException("ERROR: error reading file", e);
    }
    if (method.getStatusCode() != 200) {
        throw new BlogClientException("ERROR HTTP status=" + method.getStatusCode());
    }
    try {
        return method.getResponseBodyAsStream();
    } catch (final Exception e) {
        throw new BlogClientException("ERROR: error reading file", e);
    }
}

From source file:cn.vlabs.umt.services.session.impl.LoginRecord.java

public void logout(Date deadline) {
    Date timeout = DateUtils.addMinutes(lastupdate, 30);
    if (timeout.before(deadline)) {
        String sessionkey = sessionkeys.get(appType);
        if (sessionkey != null) {
            GetMethod method = new GetMethod(logoutURL);
            method.setRequestHeader("Connection", "close");
            method.setRequestHeader("Cookie", sessionkey + "=" + appSessionid);
            HttpClient client = new HttpClient();
            try {
                client.executeMethod(method);
            } catch (Exception e) {

            } finally {
                client.getHttpConnectionManager().closeIdleConnections(0);
            }// w  w w .j a va2 s  . com
        }
    }
}

From source file:com.prashsoft.javakiva.KivaUtil.java

public static Object getBeanResponse(String urlSuffix, String urlMethod, String urlParams) {

    Object bean = null;/*from   www  .  j  av a2s.c o m*/

    String url = createKivaAPIUrl(urlSuffix, urlMethod, urlParams);

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println(url + " :: Method failed! : " + method.getStatusLine());
            return null;
        }

        // Read the response body.

        InputStream is = method.getResponseBodyAsStream();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));

        String datastr = null;
        StringBuffer sb = new StringBuffer();

        String inputLine;

        while ((inputLine = in.readLine()) != null)
            sb.append(inputLine);

        in.close();
        is.close();

        String response = sb.toString();

        // Deal with the response.
        JSONObject jsonObject = JSONObject.fromObject(response);

        bean = JSONObject.toBean(jsonObject);

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println("Fatal general error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return bean;

}

From source file:de.mpg.imeji.presentation.servlet.ImageServlet.java

/**
 * {@inheritDoc}//from  w  w  w .  j  a v  a 2  s.  co m
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String imageUrl = req.getParameter("imageUrl");
    GetMethod method = null;
    try {
        if (imageUrl == null) {
            resp.sendError(404, "URL null");
        } else {
            method = new GetMethod(imageUrl);
            method.setFollowRedirects(false);
            if (userHandle == null) {
                userHandle = LoginHelper.login(PropertyReader.getProperty("imeji.escidoc.user"),
                        PropertyReader.getProperty("imeji.escidoc.password"));
            }
            method.addRequestHeader("Cookie", "escidocCookie=" + userHandle);
            method.addRequestHeader("Cache-Control", "public");
            method.setRequestHeader("Connection", "close");
            // Execute the method with HttpClient.
            HttpClient client = new HttpClient();
            ProxyHelper.setProxy(client, frameworkUrl);
            client.executeMethod(method);
            // byte[] input;
            InputStream input;
            if (method.getStatusCode() == 302) {
                // try again
                logger.info("try load image again");
                method.releaseConnection();
                userHandle = LoginHelper.login(
                        de.mpg.imeji.presentation.util.PropertyReader.getProperty("imeji.escidoc.user"),
                        PropertyReader.getProperty("imeji.escidoc.password"));
                method = new GetMethod(imageUrl);
                method.setFollowRedirects(true);
                method.addRequestHeader("Cookie", "escidocCookie=" + userHandle);
                client.executeMethod(method);
            }
            if (method.getStatusCode() != 200) {
                ProxyHelper.setProxy(client, PropertyReader.getProperty("escidoc.imeji.instance.url"));
                method = new GetMethod(PropertyReader.getProperty("escidoc.imeji.instance.url")
                        + "/resources/icon/defaultThumb.gif");
                client.executeMethod(method);
                // out = resp.getOutputStream();
                if (method.getStatusCode() == 302) {
                    method.releaseConnection();
                    throw new RuntimeException("error code " + method.getStatusCode());
                }
                input = method.getResponseBodyAsStream();
            } else {
                for (Header header : method.getResponseHeaders()) {
                    resp.setHeader(header.getName(), header.getValue());
                }
                input = method.getResponseBodyAsStream();
            }
            OutputStream out = resp.getOutputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            long numWritten = 0;
            while ((numRead = input.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                // out.flush();
                numWritten += numRead;
            }
            input.close();
            method.releaseConnection();
            out.flush();
            out.close();
            // ReadableByteChannel inputChannel = Channels.newChannel(input);
            // WritableByteChannel outputChannel = Channels.newChannel(out);
            // fastChannelCopy(inputChannel, outputChannel);
            // inputChannel.close();
            // outputChannel.close();
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (method != null)
            method.releaseConnection();
    }
}

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   ww  w  .j a v a  2 s . c  o m
 * @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.autentia.mvn.plugin.changes.HttpRequest.java

/**
 * Send a GET method request to the given link using the configured HttpClient, possibly following redirects, and returns
 * the response as String./*from   w w w.j  a va 2 s  .c  o m*/
 * 
 * @param cl the HttpClient
 * @param link the URL
 * @throws HttpStatusException
 * @throws IOException
 */
public byte[] sendGetRequest(final HttpClient cl, final String link) throws HttpStatusException, IOException {
    try {
        final GetMethod gm = new GetMethod(link);

        this.getLog().info("Downloading from Bugzilla at: " + link);

        gm.setFollowRedirects(true);

        cl.executeMethod(gm);

        final StatusLine sl = gm.getStatusLine();

        if (sl == null) {
            this.getLog().error("Unknown error validating link: " + link);

            throw new HttpStatusException("UNKNOWN STATUS");
        }

        // if we get a redirect, do so
        if (gm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            final Header locationHeader = gm.getResponseHeader("Location");

            if (locationHeader == null) {
                this.getLog().warn("Site sent redirect, but did not set Location header");
            } else {
                final String newLink = locationHeader.getValue();

                this.getLog().debug("Following redirect to " + newLink);

                this.sendGetRequest(cl, newLink);
            }
        }

        if (gm.getStatusCode() == HttpStatus.SC_OK) {
            final InputStream is = gm.getResponseBodyAsStream();
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final byte[] buff = new byte[256];
            int readed = is.read(buff);
            while (readed != -1) {
                baos.write(buff, 0, readed);
                readed = is.read(buff);
            }
            this.getLog().debug("Downloading from Bugzilla was successful");
            return baos.toByteArray();
        } else {
            this.getLog().warn("Downloading from Bugzilla failed. Received: [" + gm.getStatusCode() + "]");
            throw new HttpStatusException("WRONG STATUS");
        }
    } catch (final HttpException e) {
        if (this.getLog().isDebugEnabled()) {
            this.getLog().error("Error downloading issues from Bugzilla:", e);
        } else {
            this.getLog().error("Error downloading issues from Bugzilla url: " + e.getLocalizedMessage());

        }
        throw e;
    } catch (final IOException e) {
        if (this.getLog().isDebugEnabled()) {
            this.getLog().error("Error downloading issues from Bugzilla:", e);
        } else {
            this.getLog().error("Error downloading issues from Bugzilla. Cause is " + e.getLocalizedMessage());
        }
        throw e;
    }
}

From source file:com.ifeng.vdn.ip.repository.service.impl.BaiduBatchIPAddressChecker.java

@Override
public List<BaiduIPBean> check(List<String> ips) {
    List<BaiduIPBean> list = new ArrayList<BaiduIPBean>();

    BaiduIPBean ipaddress = null;// w w  w . j  ava  2s. com
    // Create an instance of HttpClient.
    HttpClient clinet = new HttpClient();

    for (String ip : ips) {

        String url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=" + ip
                + "&co=&resource_id=6006&t=1428632527853&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110204891062709502876_1428631554303&_=1428631554305";

        // Create a method instance.
        GetMethod getMethod = new GetMethod(url);

        try {
            // Execute the method.
            int statusCode = clinet.executeMethod(getMethod);

            if (statusCode != HttpStatus.SC_OK) {
                log.error("Method failedd: {}", getMethod.getStatusCode());
            } else {
                // Read the response body.
                byte[] responseBody = getMethod.getResponseBody();
                String responseStr = new String(responseBody, "GBK");

                responseStr = responseStr.substring(responseStr.indexOf("(") + 1, responseStr.indexOf(")"));

                ObjectMapper mapper = new ObjectMapper();

                ipaddress = mapper.readValue(responseStr, BaiduIPBean.class);

                list.add(ipaddress);
            }

        } catch (JsonParseException | JsonMappingException | HttpException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return list;
}

From source file:au.org.ala.commonui.util.WebUtils.java

/**
 * Retrieve contentMap as InputStream.//from   w w w .j  av  a2  s  . co  m
 * 
 * @param url
 * @return
 * @throws Exception
 */
public static InputStream getUrlContent(String url) throws Exception {
    HttpClient httpClient = new HttpClient();
    GetMethod gm = new GetMethod(url);
    httpClient.executeMethod(gm);
    return gm.getResponseBodyAsStream();
}

From source file:com.cerema.cloud2.lib.resources.shares.GetRemoteSharesOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;

    // Get Method        
    GetMethod get = null;/*from   w ww.  ja  v  a  2s .c  o  m*/

    // Get the response
    try {
        get = new GetMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH);
        get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        status = client.executeMethod(get);

        if (isSuccess(status)) {
            String response = get.getResponseBodyAsString();

            // Parse xml response and obtain the list of shares
            ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser(
                    new ShareXMLParser());
            parser.setOwnCloudVersion(client.getOwnCloudVersion());
            parser.setServerBaseUri(client.getBaseUri());
            result = parser.parse(response);
        } else {
            result = new RemoteOperationResult(false, status, get.getResponseHeaders());
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while getting remote shares ", e);

    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }
    return result;
}