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.github.adam6806.mediarequest.sonarrservice.SonarrService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    try {//from  w  w  w. j a va  2s  .c  o m
        HttpClient httpClient = new HttpClient();
        String term = request.getParameter("searchTerm");
        URI uri = new URIBuilder().setScheme(sonarrURL.getProtocol()).setHost(sonarrURL.getHost())
                .setPort(sonarrURL.getPort()).setPath("/api/Series/lookup").setParameter("term", term)
                .setParameter("apikey", apiKey).build();
        GetMethod getMethod = new GetMethod(uri.toString());
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        httpClient.executeMethod(getMethod);
        String responseBody = getMethod.getResponseBodyAsString();
        response.getWriter().write(responseBody);
    } catch (URISyntaxException ex) {
        Logger.getLogger(SonarrService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(SonarrService.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:edu.stanford.muse.webapp.HTMLToImage.java

/**
 * Convert an HTML page at the specified URL into an image who's data is
 * written to the provided output stream.
 *
 * @param url    URL to the page that is to be imaged.
 * @param os     An output stream that is to be opened for writing.  Image
 *               data will be written to the provided stream.  The stream
 *               will not be closed under any circumstances by this method.
 * @param width  The desired width of the image that will be created.
 * @param height The desired height of the image that will be created.
 *
 * @returns true if the page at the provided URL was loaded, converted to an
 *          image, and the image data has been written to the output stream,
 *          false if an error has ocurred along the way.
 *
 * @throws HTMLImagerException if an error has ocurred.
 *//*w  ww.  j a va 2s  .c o  m*/
public static boolean image(String url, OutputStream os, int width, int height) {
    if (log.isDebugEnabled())
        log.debug("Imaging url '" + url + "'.");

    boolean successful = false;

    try {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);

        httpClient.executeMethod(getMethod);

        int httpStatus = getMethod.getStatusCode();

        if (httpStatus == HttpServletResponse.SC_OK) {
            Tidy tidy = new Tidy();

            tidy.setQuiet(true);
            tidy.setXHTML(true);
            tidy.setHideComments(true);
            tidy.setInputEncoding("UTF-8");
            tidy.setOutputEncoding("UTF-8");
            tidy.setShowErrors(0);
            tidy.setShowWarnings(false);

            Document doc = tidy.parseDOM(getMethod.getResponseBodyAsStream(), null);

            if (doc != null) {
                BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = (Graphics2D) buf.getGraphics();
                Graphics2DRenderer renderer = new Graphics2DRenderer();
                SharedContext context = renderer.getSharedContext();
                UserAgentCallback userAgent = new HTMLImagerUserAgent(url);

                context.setUserAgentCallback(userAgent);
                context.setNamespaceHandler(new XhtmlNamespaceHandler());

                renderer.setDocument(doc, url);
                renderer.layout(graphics, new Dimension(width, height));
                renderer.render(graphics);
                graphics.dispose();

                /*
                JPEGEncodeParam param = JPEGCodec.getDefaultJPEGEncodeParam( buf );
                        
                param.setQuality( (float)1.0, false );
                        
                JPEGImageEncoder imageEncoder = JPEGCodec.createJPEGEncoder( os,
                      param );
                        
                imageEncoder.encode( buf );
                */
                successful = true;
            } else {
                if (log.isDebugEnabled())
                    log.debug("Unable to image URL '" + url
                            + "'.  The HTML that was returned could not be tidied.");
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Unable to image URL '" + url + "'.  Server returned status code '" + httpStatus
                        + "'.");
        }
    }

    catch (Exception e) {
        throw new RuntimeException("Unable to image URL '" + url + "'.", e);
    }

    return successful;
}

From source file:DBpediaSpotlightClient.java

@Override
public List<DBpediaResource> extract(Text text) throws AnnotationException {

    LOG.info("Querying API.");
    String spotlightResponse;/*from  w  w  w  .  ja va2 s .co  m*/
    try {
        GetMethod getMethod = new GetMethod(API_URL + "rest/annotate/?" + "confidence=" + CONFIDENCE
                + "&support=" + SUPPORT + "&text=" + URLEncoder.encode(text.text(), "utf-8"));
        getMethod.addRequestHeader(new Header("Accept", "application/json"));

        spotlightResponse = request(getMethod);
    } catch (UnsupportedEncodingException e) {
        throw new AnnotationException("Could not encode text.", e);
    }

    assert spotlightResponse != null;

    JSONObject resultJSON = null;
    JSONArray entities = null;

    try {
        resultJSON = new JSONObject(spotlightResponse);
        entities = resultJSON.getJSONArray("Resources");
    } catch (JSONException e) {
        throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
    }

    LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
    for (int i = 0; i < entities.length(); i++) {
        try {
            JSONObject entity = entities.getJSONObject(i);
            resources.add(new DBpediaResource(entity.getString("@URI"),
                    Integer.parseInt(entity.getString("@support"))));

        } catch (JSONException e) {
            LOG.error("JSON exception " + e);
        }

    }

    return resources;
}

From source file:com.predic8.membrane.core.interceptor.RegExReplaceInterceptorTest.java

@Test
public void testReplace() throws Exception {
    HttpClient client = new HttpClient();

    GetMethod method = new GetMethod("http://localhost:3009");
    method.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    method.setRequestHeader(Header.SOAP_ACTION, "");

    assertEquals(200, client.executeMethod(method));

    assertTrue(new String(method.getResponseBody()).contains("Membrane RegEx Replacement Is Cool"));
}

From source file:com.sappenin.eaut.consumer.mappingservice.MappingServiceClientImpl.java

/**
 * This function communicates with an EAUT Mapping service via an HTTP get,
 * provides the service an email address, and return the resulting URL, if
 * found.//  w  ww .  j av  a 2s .c o  m
 * 
 * @param pae
 * @return The URL that the specified Mapping Service indicates is the URL
 *         of the specified email address.
 * @throws EAUTException
 */
@Override
public String queryMappingService(ParsedEmailAddress pae, String getUrl) throws EAUTException {
    HttpClient client = new HttpClient();
    GetMethod get = new GetMethod(getUrl);
    get.setFollowRedirects(true);

    if (log.isDebugEnabled())
        log.debug("Performing HTTP GET on: " + getUrl + " ...");

    int statusCode;
    try {
        statusCode = client.executeMethod(get);
        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode == HttpStatus.SC_BAD_REQUEST)
                throw new EAUTException("The Email Identifier supplied by '" + getUrl
                        + "' is not properly formatted per the EAUT spec and/or RFC2822 (Http Error 400)");
            else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR)
                throw new EAUTException(
                        "The EAUT Mapping Service was unable to complete a mapping request for URL: '" + getUrl
                                + "'.  Please try this request again at a later time.  (Http Error 500)");
            else
                throw new EAUTException("GET failed on " + getUrl + "(Http Error " + statusCode + ")");
        } else {
            String redirectLocation = get.getURI().toString();
            if (redirectLocation != null) {
                return redirectLocation;
            } else {
                // The response is invalid and did not provide the new
                // location
                // for the resource. Report an error or possibly handle the
                // response like a 404 Not Found error.
                throw new EAUTException("GET failed on " + getUrl + "(Http Error " + statusCode + ")");
            }

        }
    } catch (EAUTException ee) {
        throw ee;
    } catch (HttpException he) {
        throw new EAUTException(he);
    } catch (IOException ioe) {
        throw new EAUTException(ioe);
    }
}

From source file:com.thoughtworks.go.agent.launcher.ServerCallTest.java

@Test
public void shouldThrowSpecifiCExceptionIncaseOf404() throws Exception {
    GetMethod getMethod = new GetMethod("http://localhost:9090/go/not-found");
    try {// w  w  w  .  j  a v  a  2  s  . com
        ServerCall.invoke(getMethod);
    } catch (Exception ex) {
        assertThat(ex.getMessage().contains("This agent might be incompatible with your Go Server."
                + "Please fix the version mismatch between Go Server and Go Agent."), is(true));
    }

}

From source file:com.github.adam6806.mediarequest.couchpotatoservice.CouchPotatoService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    try {/*from w  ww  .  j  a va 2s  .  com*/
        HttpClient httpClient = new HttpClient();
        String term = request.getParameter("searchTerm");
        URI uri = new URIBuilder().setScheme(couchPotatoURL.getProtocol()).setHost(couchPotatoURL.getHost())
                .setPort(couchPotatoURL.getPort()).setPath("/api/" + apiKey + "/movie.search")
                .setParameter("q", term).build();
        GetMethod getMethod = new GetMethod(uri.toString());
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        httpClient.executeMethod(getMethod);
        String responseBody = getMethod.getResponseBodyAsString();
        response.getWriter().write(responseBody);
    } catch (URISyntaxException ex) {
        Logger.getLogger(CouchPotatoService.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CouchPotatoService.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.predic8.membrane.integration.ProxySSLConnectionMethodTest.java

@Test
public void testSSLConnectionMethod() throws Exception {
    HttpClient client = new HttpClient();
    client.getHostConfiguration().setProxy("localhost", 3129);

    GetMethod post = new GetMethod("https://www.google.com/");
    client.executeMethod(post);//  w  w w.j  a  v a 2  s.com
    AssertUtils.assertContains("<html", post.getResponseBodyAsString());

    client.getHttpConnectionManager().closeIdleConnections(0);
}

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

public InputStream getModel(String modelId, String type) {
    HttpClient httpClient = getClient();

    String uri = REST_URI + "/learnpad/model/" + modelId;
    GetMethod getMethod = new GetMethod(uri);
    NameValuePair[] queryString = new NameValuePair[1];
    queryString[0] = new NameValuePair("type", type);
    getMethod.setQueryString(queryString);
    getMethod.addRequestHeader("Accept", "application/xml");
    getMethod.addRequestHeader("Accept-Ranges", "bytes");

    try {/*from w  w w  . j  a v a 2  s .c om*/
        httpClient.executeMethod(getMethod);
    } catch (HttpException e) {
        logger.error("Unable to process the GET request for model '" + modelId + "' (" + type + ").", e);
        return null;
    } catch (IOException e) {
        logger.error("Unable to GET the '" + modelId + "' model (" + type + ").", e);
        return null;
    }
    try {
        return getMethod.getResponseBodyAsStream();
    } catch (IOException e) {
        logger.error("Unable to extract the '" + modelId + "' model (" + type + ") from GET response.", e);
        return null;
    }
}

From source file:com.dianping.lion.db.DataSourceFetcher.java

/**
 * ??DB?/* w  w w.ja  va2 s.  c  om*/
 * @param lastFetchTime ?
 * @return
 */
public String fetchDS(long lastFetchTime) {
    String dsContent = null;
    long minEffectionTime = System.currentTimeMillis() / 60000 + 10;
    String url = path + lastFetchTime + "&srtkey=" + srtkey + minEffectionTime;
    dsGetter = new GetMethod(url);
    try {
        httcClient.executeMethod(dsGetter);
        InputStream inputStream = dsGetter.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String str = "";
        while ((str = br.readLine()) != null) {
            stringBuffer.append(str);
        }
        dsContent = stringBuffer.toString();
    } catch (Exception e) {
        logger.error("Job execution failed this time.", e);
        return null;
    }
    return dsContent;
}