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.neurowork.cenatic.centraldir.workers.xml.AbstractXmlImporter.java

protected T findRestEntity(Object id) {
    HttpClient httpclient = XMLRestWorker.getHttpClient();
    GetMethod get = new GetMethod(getRestUrl());
    get.addRequestHeader("Accept", "application/xml");
    T ret = null;//  w w w  . jav  a 2 s.co  m
    try {
        int result = httpclient.executeMethod(get);
        logger.info("Response status code: " + result);
        String xmlString = get.getResponseBodyAsString();
        logger.info("Response body: " + xmlString);

        ret = importEntity(xmlString, id);
    } catch (HttpException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
        logger.error(e.getMessage());
    } catch (SAXException e) {
        logger.error(e.getMessage());
    } finally {
        get.releaseConnection();
    }
    return ret;
}

From source file:net.mojodna.searchable.solr.SolrSearcher.java

public ResultSet search(final String query, final Integer start, final Integer count) throws IndexException {
    try {//from  w w  w.  j  a v  a2 s .c o  m
        final GetMethod get = new GetMethod(solrPath);
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("q", query));
        if (null != start) {
            params.add(new NameValuePair("start", start.toString()));
        }
        if (null != count) {
            params.add(new NameValuePair("rows", count.toString()));
        }
        params.add(new NameValuePair("version", "2.1"));
        params.add(new NameValuePair("indent", "on"));
        get.setQueryString(params.toArray(new NameValuePair[] {}));
        final int responseCode = getHttpClient().executeMethod(get);

        final SAXBuilder builder = new SAXBuilder();
        final Document response = builder.build(get.getResponseBodyAsStream());
        final Element resultNode = response.getRootElement().getChild("result");

        final ResultSetImpl resultSet = new ResultSetImpl(
                new Integer(resultNode.getAttributeValue("numFound")));
        resultSet.setOffset(new Integer(resultNode.getAttributeValue("start")));
        List<Element> docs = resultNode.getChildren("doc");
        for (int i = 0; i < docs.size(); i++) {
            final Element doc = docs.get(i);
            Result result = null;

            // load the class name
            String className = null;
            String id = null;
            String idType = null;
            for (final Iterator it = doc.getChildren("str").iterator(); it.hasNext();) {
                final Element str = (Element) it.next();
                final String name = str.getAttributeValue("name");
                if (IndexSupport.TYPE_FIELD_NAME.equals(name)) {
                    className = str.getTextTrim();
                } else if (IndexSupport.ID_FIELD_NAME.equals(name)) {
                    id = str.getTextTrim();
                } else if (IndexSupport.ID_TYPE_FIELD_NAME.equals(name)) {
                    idType = str.getTextTrim();
                }
            }

            try {
                // attempt to instantiate an instance of the specified class
                try {
                    if (null != className) {
                        final Object o = Class.forName(className).newInstance();
                        if (o instanceof Result) {
                            log.debug("Created new instance of: " + className);
                            result = (Result) o;
                        }
                    }
                } catch (final ClassNotFoundException e) {
                    // class was invalid, or something
                }

                // fall back to a GenericResult as a container
                if (null == result)
                    result = new GenericResult();

                if (result instanceof Searchable) {
                    // special handling for searchables
                    final String idField = SearchableBeanUtils
                            .getIdPropertyName(((Searchable) result).getClass());

                    // attempt to load the id and set the id property on the Searchable appropriately
                    if (null != id) {
                        log.debug("Setting id to '" + id + "' of type " + idType);
                        try {
                            final Object idValue = ConvertUtils.convert(id, Class.forName(idType));
                            PropertyUtils.setSimpleProperty(result, idField, idValue);
                        } catch (final ClassNotFoundException e) {
                            log.warn("Id type was not a class that could be found: " + idType);
                        }
                    } else {
                        log.warn("Id value was null.");
                    }
                } else {
                    final GenericResult gr = new GenericResult();
                    gr.setId(id);
                    gr.setType(className);
                    result = gr;
                }

            } catch (final Exception e) {
                throw new SearchException("Could not reconstitute resultant object.", e);
            }

            result.setRanking(i);

            resultSet.add(result);
        }

        return resultSet;
    } catch (final JDOMException e) {
        throw new IndexingException(e);
    } catch (final IOException e) {
        throw new IndexingException(e);
    }
}

From source file:edu.unc.lib.dl.ui.service.DjatokaContentService.java

public void getMetadata(String simplepid, String datastream, OutputStream outStream,
        HttpServletResponse response, int retryServerError) {
    HttpClientParams params = new HttpClientParams();
    params.setContentCharset("UTF-8");
    HttpClient client = new HttpClient();
    client.setParams(params);//w  w w .  j a  v a 2 s.co m

    StringBuilder path = new StringBuilder(applicationPathSettings.getDjatokaPath());
    path.append("resolver?url_ver=Z39.88-2004&rft_id=")
            .append(applicationPathSettings.getFedoraPathWithoutDefaultPort()).append("/objects/")
            .append(simplepid).append("/datastreams/").append(datastream).append("/content")
            .append("&svc_id=info:lanl-repo/svc/getMetadata");

    GetMethod method = new GetMethod(path.toString());
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            if (response != null) {
                response.setHeader("Content-Type", "application/json");
                response.setHeader("content-disposition", "inline");

                FileIOUtil.stream(outStream, method);
            }
        } else {
            if ((method.getStatusCode() == 500 || method.getStatusCode() == 404) && retryServerError > 0) {
                this.getMetadata(simplepid, datastream, outStream, response, retryServerError - 1);
            } else {
                LOG.error("Unexpected failure: " + method.getStatusLine().toString());
                LOG.error("Path was: " + method.getURI().getURI());
            }
        }
    } catch (ClientAbortException e) {
        if (LOG.isDebugEnabled())
            LOG.debug("User client aborted request to stream jp2 metadata for " + simplepid, e);
    } catch (Exception e) {
        LOG.error("Problem retrieving metadata for " + path, e);
    } finally {
        method.releaseConnection();
    }
}

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

/**
 * Retrieve contentMap as String./*from   w  w  w  .  j ava 2 s  .co m*/
 * 
 * @param url
 * @return
 * @throws Exception
 */
public static String getUrlContentAsString(String url) throws Exception {
    HttpClient httpClient = new HttpClient();
    GetMethod gm = new GetMethod(url);
    gm.setFollowRedirects(true);
    httpClient.executeMethod(gm);
    String content = "[ERROR: external content request failed - see tomcat logs]";
    logger.debug("GET status code = " + gm.getStatusCode());
    // String requestCharset = gm.getRequestCharSet();

    if (gm.getStatusCode() == 200) {
        content = gm.getResponseBodyAsString();
    }

    return content;
}

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

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*  w  ww  . j a v a 2s . c o  m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String suggest = request.getParameter("searchkeyword");
    String datasource = request.getParameter("datasource");
    String responseString = "";
    if (suggest.isEmpty()) {
        suggest = "a";
    } else if (datasource != null && !datasource.isEmpty()) {
        HttpClient client = new HttpClient();
        GetMethod getMethod = new GetMethod(datasource + URLEncoder.encode(suggest.toString(), "UTF-8"));
        try {
            client.executeMethod(getMethod);
            responseString = new String(StorageUtils.toBytes(getMethod.getResponseBodyAsStream()), "UTF-8");
            if (datasource != null && responseString != null)
                responseString = passResult(responseString, datasource);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getMethod.releaseConnection();
        }
    }
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    out.print(responseString);
    out.flush();
    out.close();
}

From source file:ch.ksfx.web.services.spidering.http.HttpClientHelper.java

/**
 * Returns an executed GetMethod object with the given URL
 *
 * @param url URL for HTTP GET request//  www . j  a  v  a  2 s  .c o m
 * @return executed GetMethod object
 */
public GetMethod executeGetMethod(String url) {
    url = encodeURL(url);
    GetMethod getMethod = new GetMethod(url);
    getMethod.setFollowRedirects(true);
    getMethod = (GetMethod) executeMethod(getMethod);
    return getMethod;
}

From source file:com.zimbra.cs.util.yauth.TokenAuthenticateV1.java

/**
 * @param username// www  .  ja v a 2s.  co  m
 * @param token THIS IS NOT THE PASSWORD -- use the static getToken() method
 *              to get the user's token
 * @return
 */
public static TokenAuthenticateV1 doAuth(String username, String token) throws IOException, HttpException {
    GetMethod method = new GetMethod("https://login.yahoo.com/config/pwtoken_login?src=ymsgr&token=" + token);
    int response = HttpClientUtil.executeMethod(method);

    if (response >= 200 && response < 300) {
        String body = method.getResponseBodyAsString();

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("crumb", null);
        map.put("Y", null);
        map.put("T", null);

        parseResponseBody(body, map);

        return new TokenAuthenticateV1(map.get("crumb"), map.get("Y"), map.get("T"));
    } else {
        throw new IOException("HTTPClient response: " + response);
    }
}

From source file:com.google.apphosting.vmruntime.jetty9.VmRuntimeJettyAuthTest.java

public void testAuth_UserRequiredWithUser() throws Exception {
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    GetMethod get = new GetMethod(createUrl("/user/test-auth").toString());
    get.addRequestHeader(VmApiProxyEnvironment.EMAIL_HEADER, "isdal@google.com");
    get.addRequestHeader(VmApiProxyEnvironment.AUTH_DOMAIN_HEADER, "google.com");
    get.setFollowRedirects(false);//ww w .  ja va 2s  .c om
    int httpCode = httpClient.executeMethod(get);
    assertEquals(200, httpCode);
    assertEquals("isdal@google.com: isdal@google.com", get.getResponseBodyAsString());
}

From source file:de.ingrid.iplug.opensearch.communication.OSCommunication.java

/**
 * Send a request with all parameters within the "url"-String.
 * /*from   ww  w  .j  a v a2  s . c  o m*/
 * @param url is the URL to request including the parameters
 * @return the response of the request
 */
public InputStream sendRequest(String url) {
    try {
        HttpClientParams httpClientParams = new HttpClientParams();
        HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager();
        httpClientParams.setSoTimeout(30 * 1000);
        httpConnectionManager.getParams().setConnectionTimeout(30 * 1000);
        httpConnectionManager.getParams().setSoTimeout(30 * 1000);

        HttpClient client = new HttpClient(httpClientParams, httpConnectionManager);
        method = new GetMethod(url);

        // set a request header
        // this can change in the result of the response since it might be 
        // interpreted differently
        //method.addRequestHeader("Accept-Language", language); //"de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");

        int status = client.executeMethod(method);
        if (status == 200) {
            log.debug("Successfully received: " + url);
            return method.getResponseBodyAsStream();
        } else {
            log.error("Response code for '" + url + "' was: " + status);
            return null;
        }
    } catch (HttpException e) {
        log.error("An HTTP-Exception occured when calling: " + url);
        e.printStackTrace();
    } catch (IOException e) {
        log.error("An IO-Exception occured when calling: " + url);
        e.printStackTrace();
    }
    return null;
}

From source file:com.abee.InteractiveAuthenticationExample.java

private void doDemo() throws IOException {

    HttpClient client = new HttpClient();
    client.getParams().setParameter(CredentialsProvider.PROVIDER, new ConsoleAuthPrompter());
    GetMethod httpget = new GetMethod("http://www.lauramares.com/kaira");
    httpget.setDoAuthentication(true);/*from  w  w w .  j  av  a  2  s  . com*/
    try {
        // execute the GET
        int status = client.executeMethod(httpget);
        // print the status and response
        System.out.println(httpget.getStatusLine().toString());
        System.out.println(httpget.getResponseBodyAsString());
    } finally {
        // release any connection resources used by the method
        httpget.releaseConnection();
    }
}