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.kenware.langtrans.GoogleTranslater.java

/**
 * translates source string (sin) into a response using the source/target
 * languages./*from   w  w  w . jav a2s. c  om*/
 *
 * @param sin String in
 * @param sourcelang source language (ISO3166 code)
 * @param targetlang target language (ISO3166 code)
 * @return returns a text string in the target language
 */
public String urlTranslate(String sin, String sourcelang, String targetlang) {
    String response = "";
    String url = null;
    HttpClient client = new HttpClient();
    HttpMethod method = null;
    String responsebody = null;

    try {
        String s = URLEncoder.encode(sin, "UTF-8");
        url = "http://google.com/translate_t?hl=en&ie=UTF8&text=" + s + "&langpair=" + sourcelang + "%7C"
                + targetlang;
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        method = new GetMethod(url);
        method.setFollowRedirects(true);

        client.executeMethod(method);
        responsebody = method.getResponseBodyAsString();
        method.releaseConnection();

        response = extractResponse(responsebody);

    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());

    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");

    } catch (Exception ex) {
        System.err.println("EXCEPTION: " + ex.getMessage());
    } // end-try-catch

    return (response);
}

From source file:net.neurowork.cenatic.centraldir.workers.XMLPushTest.java

@Test
public void testPushOrganizacion() {
    GetMethod get = new GetMethod(restUrl.getTokenUrl());
    get.addRequestHeader("Accept", "application/xml");

    NameValuePair userParam = new NameValuePair(USERNAME_PARAM, user);
    NameValuePair passwordParam = new NameValuePair(PASSWORD_PARAM, password);
    NameValuePair[] params = new NameValuePair[] { userParam, passwordParam };

    get.setQueryString(params);//  w w  w . j ava 2 s.c  om

    try {
        int result = httpclient.executeMethod(get);
        logger.info("Response status code: " + result);
        logger.info("Response body: ");
        logger.info(get.getResponseBodyAsString());

        String token = XMLRestWorker.parseToken(get.getResponseBodyAsString());
        if (token != null) {
            pushOrganization(token);
        }
    } 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();
    }

}

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

public IPAddress ipCheckByGet(String ip) {
    AliIPBean ipaddress = null;// www  .jav a 2  s. co m

    String url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;

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

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

    // Execute the method.
    // Read the response body.
    try {

        int resultCode = clinet.executeMethod(getMethod);

        if (resultCode == HttpStatus.SC_OK) {
            InputStream responseBody = getMethod.getResponseBodyAsStream();

            ObjectMapper mapper = new ObjectMapper();
            ipaddress = mapper.readValue(responseBody, AliIPBean.class);

            log.info(responseBody.toString());
        } else {
            log.error("Method failedd: [{}] , IP: [{}]", getMethod.getStatusCode(), ip);
        }

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

    return ipaddress;
}

From source file:com.rometools.propono.atom.client.EntryIterator.java

private void getNextEntries() throws ProponoException {
    if (nextURI == null) {
        return;/*  w  w  w . j  a  v  a 2  s  . c o m*/
    }
    final GetMethod colGet = new GetMethod(collection.getHrefResolved(nextURI));
    collection.addAuthentication(colGet);
    try {
        collection.getHttpClient().executeMethod(colGet);
        final SAXBuilder builder = new SAXBuilder();
        final Document doc = builder.build(colGet.getResponseBodyAsStream());
        final WireFeedInput feedInput = new WireFeedInput();
        col = (Feed) feedInput.build(doc);
    } catch (final Exception e) {
        throw new ProponoException("ERROR: fetching or parsing next entries, HTTP code: "
                + (colGet != null ? colGet.getStatusCode() : -1), e);
    } finally {
        colGet.releaseConnection();
    }
    members = col.getEntries().iterator();
    col.getEntries().size();

    nextURI = null;
    final List<Link> altLinks = col.getOtherLinks();
    if (altLinks != null) {
        for (final Link link : altLinks) {
            if ("next".equals(link.getRel())) {
                nextURI = link.getHref();
            }
        }
    }
}

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

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

    client.executeMethod(method);/*  w w  w .j  av a 2s. c o  m*/
    String message = method.getResponseBodyAsString();
    assertTrue(message.contains("Called the page /login"));
}

From source file:ensen.controler.DBpediaLookupClient.java

public Model qetEntities(String query, String classes, int numberOfRes) throws Exception {

    HttpClient client = new HttpClient();
    // client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    String query2 = URLEncoder.encode(query, "utf-8");
    HttpMethod method = new GetMethod(
            gatway + "QueryString=" + query2 + "&QueryClass=" + classes + "&MaxHits=" + numberOfRes);
    // method.setFollowRedirects(true);
    try {//from   w ww .jav  a 2s .  c  o  m
        client.executeMethod(method);
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.out.println("Http error connecting to lookup.dbpedia.org");
    } catch (IOException ioe) {
        System.out.println("Unable to connect to lookup.dbpedia.org");
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
    method.releaseConnection();

    Model model = ModelFactory.createDefaultModel();
    Resource core = model.createResource("http://ensen.org/data#q-" + query2);

    int num_results = Results.size();
    if (num_results > 0) {
        for (DBpediaLookupResModel res : Results) {
            // System.out.println("URI: " + res.uri);
            if (res.uri.contains("http://")) {
                Resource O = model.createResource(res.uri);
                Property P = model.createProperty("http://ensen.org/data#has-a");
                Literal O1 = model.createLiteral(res.label + "");
                Literal O2 = model.createLiteral(res.desc + "");
                Property P1 = model.createProperty("http://www.w3.org/2000/01/rdf-schema#label");
                Property P2 = model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#description");
                O.addProperty(P1, O1);
                O.addProperty(P2, O2);

                for (String cat : res.cats) {
                    Resource OO = model.createResource(cat);
                    Property PP = model.createProperty("http://purl.org/dc/terms/subject");
                    O.addProperty(PP, OO);
                }
                for (String c : res.classes) {
                    Resource OO = model.createResource(c);
                    Property PP = model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
                    O.addProperty(PP, OO);
                }
                core.addProperty(P, O);
            }
        }
    }

    return model;
}

From source file:davmail.util.ClientCertificateTest.java

public void testGetRoot() throws IOException {
    GetMethod getMethod = new GetMethod("/");
    httpClient.executeMethod(getMethod);
}

From source file:CertStreamCallback.java

private static HttpMethod getHttpMethod(String url, String method) {
    if ("delete".equals(method)) {
        return new DeleteMethod(url);

    } else if ("get".equals(method)) {
        return new GetMethod(url);

    } else if ("post".equals(method)) {
        return new PostMethod(url);

    } else if ("put".equals(method)) {
        return new PutMethod(url);

    } else {/*from  w  ww .ja  v a2s . c  om*/
        throw ActionException.create(ClientMessages.NO_METHOD1, method);
    }
}

From source file:com.cognifide.actions.msg.push.active.PushClientRunnable.java

private void connect() throws IOException {
    final HttpMethod method = new GetMethod(serverUrl + SERVLET_PATH);
    if (client.executeMethod(method) != 200) {
        return;/*  w w  w .  ja  va2 s  .co  m*/
    }
    final InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream());
    final BufferedReader bufferedReader = new BufferedReader(reader);

    String msgId;
    while ((msgId = bufferedReader.readLine()) != null) {
        final String topic = bufferedReader.readLine();
        final String msg = bufferedReader.readLine();
        LOG.debug("Got message with id " + msgId);
        for (PushReceiver r : receivers) {
            r.gotMessage(topic, msg);
        }
        try {
            confirm(msgId);
            LOG.debug("Message " + msgId + " confirmed");
        } catch (IOException e) {
            LOG.error("Can't confirm message " + msgId, e);
        }
    }
    method.releaseConnection();
}

From source file:eu.eco2clouds.accounting.bonfire.BFClientAccountingImpl.java

private String getMethod(String url, Boolean exception) {
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    GetMethod method = new GetMethod(url);
    setHeaders(method);//from  w ww .ja va 2  s .  c o  m

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

    String response = "";

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

        if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... 
            logger.warn(
                    "get managed experiments information... : " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}