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.openkm.openmeetings.service.RestService.java

/**
 * call/*from  w  w w  .  j  a  v  a 2s  . c  om*/
 * 
 * @param request
 * @param param
 * @return
 * @throws Exception
 */
public static Map<String, Element> callMap(String request, Object param) throws Exception {
    HttpClient client = new HttpClient();
    GetMethod method = null;
    try {
        method = new GetMethod(getEncodetURI(request).toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    int statusCode = 0;
    try {
        statusCode = client.executeMethod(method);
    } catch (HttpException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    } catch (IOException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    }

    switch (statusCode) {
    case 200: // OK
        break;
    case 400:
        throw new Exception(
                "Bad request. The parameters passed to the service did not match as expected. The Message should tell you what was missing or incorrect.");
    case 403:
        throw new Exception(
                "Forbidden. You do not have permission to access this resource, or are over your rate limit.");
    case 503:
        throw new Exception(
                "Service unavailable. An internal problem prevented us from returning data to you.");
    default:
        throw new Exception("Your call to OpenMeetings! Web Services returned an unexpected  HTTP status of: "
                + statusCode);
    }

    InputStream rstream = null;
    try {
        rstream = method.getResponseBodyAsStream();
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("No Response Body");
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    SAXReader reader = new SAXReader();
    Document document = null;
    String line;
    try {
        while ((line = br.readLine()) != null) {
            document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new Exception("UnsupportedEncodingException by SAXReader");
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("IOException by SAXReader in REST Service");
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new Exception("DocumentException by SAXReader in REST Service");
    } finally {
        br.close();
    }

    Element root = document.getRootElement();
    Map<String, Element> elementMap = new LinkedHashMap<String, Element>();

    for (@SuppressWarnings("unchecked")
    Iterator<Element> it = root.elementIterator(); it.hasNext();) {
        Element item = it.next();
        if (item.getNamespacePrefix() == "soapenv") {
            throw new Exception(item.getData().toString());
        }
        String nodeVal = item.getName();
        elementMap.put(nodeVal, item);
    }

    return elementMap;
}

From source file:com.taobao.ad.easyschedule.commons.utils.WangWangUtil.java

/**
 * ??//  w w w  . j a va2  s .  co  m
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendWangWang(String list, String subject, String content) {

    if ("false".equals(Constants.SENDWANGWANG) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)
            || StringUtils.isEmpty(content)) {
        return;
    }
    try {
        String command = Constants.WANGWANG_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = content;
        if (content.getBytes().length > 900) {
            strContent = StringUtil.bSubstring(content, 899);
        }
        command = command.replaceAll("#list#", URLEncoder.encode(list, "GBK"))
                .replaceAll("#subject#", URLEncoder.encode(strSubject, "GBK")).replaceAll("#content#",
                        URLEncoder.encode(StringUtils.isEmpty(strContent) ? "null" : strContent, "GBK"));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.NOTIFY_API_CONN_TIMEOUT);
        GetMethod getMethod = new GetMethod(command);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        for (int i = 1; i <= 3; i++) {
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("WangWangUtil.sendWangWang statusCode:" + statusCode);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                String ret = getMethod.getResponseBodyAsString();
                if (!"OK".equals(ret)) {
                    logger.error("Send message failed[" + i + "];list:" + list + ";subject:" + subject
                            + ";content:" + content);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                logger.error("Send message failed[" + i + "]:" + e.getMessage());
                Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("WangWangUtil.sendWangWang", e);
    }
}

From source file:jshm.sh.scraper.wiki.ActionsScraper.java

public static Map<String, List<Action>> scrape(String wikiUrl, final Map<String, List<Action>> ret)
        throws IOException, ScraperException {
    if (!wikiUrl.endsWith("/raw"))
        wikiUrl = wikiUrl + "/raw";

    HttpClient client = Client.getHttpClient();
    GetMethod method = new GetMethod(wikiUrl);
    client.executeMethod(method);// w w  w.  ja v a  2s  . c  o m

    if (method.getStatusCode() != 200) {
        LOG.warning("Non-200 response for " + wikiUrl + " - " + method.getStatusLine());
        return ret;
    }

    String charset = method.getResponseCharSet();
    LOG.fine("Charset for HTTP response is: " + charset);
    if (null == charset || charset.isEmpty())
        charset = "ISO-8859-1";

    return scrape(new InputStreamReader(method.getResponseBodyAsStream(), charset), ret);
}

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

@Test
public void shouldBeAbleToReadTheResponseBody() throws Exception {
    GetMethod getMethod = new GetMethod(
            DownloadableFile.AGENT.url(ServerUrlGeneratorMother.generatorFor("localhost", 9090)));
    ServerCall.ServerResponseWrapper response = ServerCall.invoke(getMethod);
    List list = IOUtils.readLines(response.body);
    assertThat(list.isEmpty(), is(false));
}

From source file:function.GetPhotoInfo.java

private void getPhotoInfo(Photo photo)
        throws IOException, ParserConfigurationException, SAXException, JSONException {

    setRequest(getData().getRequestMethod() + getData().getMethodGetInfo() + "&photo_id=" + photo.getId()
            + "&api_key=" + getData().getKey() + "&format=json");
    System.out.println("GET info request: " + getRequest());

    setMethod(new GetMethod(getRequest()));
    setStatusCode(getClient().executeMethod(getMethod()));

    if (getStatusCode() != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + getMethod().getStatusLine());
    }// ww  w .j  a  v  a  2s. c  o m
    setRstream(null);
    setRstream(getMethod().getResponseBodyAsStream());

    String jstr = toString(getRstream());
    jstr = jstr.substring("jsonFlickrApi(".length(), jstr.length() - 1);

    JSONObject jobj = new JSONObject(jstr);
    JSONObject owner = jobj.getJSONObject("photo").getJSONObject("owner");

    photo.setLocation(owner.getString("location"));
    photo.setLat(0);
    photo.setLon(0);

}

From source file:com.music.service.PurchaseService.java

public static void main(String[] args) throws Exception {
    HttpClient client = new HttpClient();
    String url = "https://coinbase.com/api/v1/currencies/exchange_rates?api_key=226d24b176455557d2928e54321b5ec35fd6e054d9d682ad0927f4e7ea6ed7b1";
    GetMethod get = new GetMethod(url);
    get.setRequestHeader("Content-Type", "application/json");
    get.setRequestHeader("Accept", "application/json");
    get.setRequestHeader("User-Agent", "");
    client.executeMethod(get);//from  w  w  w.j  a va  2  s.  c  o m
    System.out.println(new String(get.getResponseBody()));
}

From source file:net.jadler.AbstractJadlerStubbingResponseHeadersTest.java

@Test
public void allHeaders() throws IOException {
    onRequest().respond().withBody("13 chars long");

    final GetMethod method = new GetMethod("http://localhost:" + port());
    client.executeMethod(method);/*www  .  ja va 2  s. c o  m*/

    final Header[] responseHeaders = method.getResponseHeaders();

    for (final Header h : responseHeaders) {
        System.out.println(h.getName() + ": " + h.getValue());
    }

    assertThat(responseHeaders.length, is(2));

    assertThat(method.getResponseHeader("Date"), is(notNullValue()));
    assertThat(method.getResponseHeader("Content-Length").getValue(), is("13"));
}

From source file:com.lyncode.performance.PerformanceRequester.java

public void requestDurationWithoutSum(String url) throws IOException {
    GetMethod getMethod = new GetMethod(BASE + url);
    //        long start = nanoTime();
    //        System.out.println("Start: "+start);
    client.executeMethod(getMethod);//www  . j a  v  a2  s  .c om
    getMethod.getResponseContentLength();
    //        long end = nanoTime();
    //        System.out.println("End: "+end);
    //        measurements.add(end - start);
}

From source file:HttpClientWrapper.java

public byte[] doRawGet(String url) {
    GetMethod method = new GetMethod(url);
    try {//from   ww w  . ja va  2s.co m
        int statusCode = doGet(method);
        return method.getResponseBody();

    } catch (Exception e) {
        ExceptionUtils.rethrow(e); // this dependency is internal only
    } finally {
        method.releaseConnection();
    }
    return null;
}

From source file:$.EndpointIT.java

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

        GetMethod method = new GetMethod(URL);

        try {/* w ww  .  j a  va 2 s.  c o  m*/
            int statusCode = client.executeMethod(method);

            assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode);

            String response = method.getResponseBodyAsString(1000);

            assertTrue("Unexpected response body", response.contains("Hello! How are you today?"));
        } finally {
            method.releaseConnection();
        }
    }