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:function.SettingCountryGeo.java

private void setCountry(String location, Photo photo) throws IOException, JSONException {

    String url = "http://api.geonames.org/searchJSON?q=" + location + "&maxRows=1&username=jelena_tabas";

    setRequest(url);/*from w  w  w  .  j a  v a 2  s.  c  om*/
    setMethod(new GetMethod(getRequest()));

    setStatusCode(getClient().executeMethod(getMethod()));

    if (getStatusCode() != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + getMethod().getStatusLine());
    }
    setRstream(null);
    setRstream(getMethod().getResponseBodyAsStream());

    String jstr = toString(getRstream());
    JSONObject jobj = new JSONObject(jstr);
    JSONArray geonames = jobj.getJSONArray("geonames");

    for (int i = 0; i < geonames.length(); i++) {
        JSONObject jphoto = geonames.getJSONObject(i);
        photo.setLocation(jphoto.getString("countryName"));
        photo.setLon(jphoto.getDouble("lng"));
        photo.setLat(jphoto.getDouble("lat"));
    }

}

From source file:com.knowledgebooks.rdf.SparqlClient.java

public SparqlClient(String endpoint_URL, String sparql) throws Exception {
    //System.out.println("SparqlClient("+endpoint_URL+", "+sparql+")");
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);

    String req = URLEncoder.encode(sparql, "utf-8");
    HttpMethod method = new GetMethod(endpoint_URL + "?query=" + req);
    method.setFollowRedirects(false);/*ww  w  . j  a va 2 s.  c om*/
    try {
        client.executeMethod(method);
        //System.out.println(method.getResponseBodyAsString());
        //if (true) return;
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + endpoint_URL + "'");
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + endpoint_URL + "'");
    }
    method.releaseConnection();
}

From source file:UsingHttpClientInsideThread.java

public MethodThread(HttpClient client, HostConfiguration host, String resource) {
    this.client = client;
    this.host = host;
    this.method = new GetMethod(resource);
}

From source file:com.simplifide.core.net.LicenseConnection.java

public void connect() {
    HttpClientParams params = new HttpClientParams();
    params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
    params.setIntParameter(HttpClientParams.MAX_REDIRECTS, 4);

    HttpClient client = new HttpClient(params);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);

    GetMethod post = new GetMethod("http://simplifide.com/drupal/free_trial2");
    post.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    /* NameValuePair[] data = {
        new NameValuePair("user_name", "joe"),
        new NameValuePair("password", "aaa"),
        new NameValuePair("name", "joker"),
        new NameValuePair("email", "beta"),
      };//  w w w  . j ava  2 s . c o  m
      post.setRequestBody(data);
      */
    try {
        int rettype = client.executeMethod(post);

        byte[] responseBody = post.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        String tstring = new String(responseBody);

    } catch (HttpException e) {

        HardwareLog.logError(e);
    } catch (IOException e) {

        HardwareLog.logError(e);
    } finally {
        post.releaseConnection();
    }

}

From source file:net.sourceforge.jcctray.model.DashboardXmlParser.java

public static DashBoardProjects getProjects(String url, HttpClient client)
        throws HttpException, IOException, SAXException {
    GetMethod method = new GetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    try {/*from ww  w  .j  a v a2 s .c o  m*/
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new RuntimeException(
                    ("Could not connect to " + url + ". The server returned a " + statusCode + " status code"));
        }
        return getProjects(method.getResponseBodyAsStream());
    } finally {
        method.releaseConnection();
    }
}

From source file:datasoul.util.OnlineUpdateCheck.java

@Override
public void run() {

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(ONLINE_BASE_URL + "latest-version");
    try {/* w w  w. j  av a2  s  . c  om*/
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            return;
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        String resp = new String(responseBody);

        // Expected format is: <NUMBER>;<NEW VERSION>;<URL>
        String toks[] = resp.split(";");

        if (toks.length != 3) {
            return;
        }

        int latestversion = Integer.parseInt(toks[0]);

        if (latestversion > VERSION) {
            String msg = java.util.ResourceBundle.getBundle("datasoul/internationalize")
                    .getString("NEW DATASOUL VERSION") + " " + toks[1] + " "
                    + java.util.ResourceBundle.getBundle("datasoul/internationalize")
                            .getString("IS AVAILABLE AT")
                    + " " + toks[2];

            ObjectManager.getInstance().getDatasoulMainForm().setInfoText(msg);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

}

From source file:com.assemblade.client.Login.java

public Authentication login(String username, String password)
        throws ChangePasswordException, CallFailedException {
    GetMethod method = new GetMethod(baseUrl + "/login");
    try {/*from   ww w .ja  v a2s .  co m*/
        method.setQueryString(new NameValuePair[] { new NameValuePair("username", username),
                new NameValuePair("password", password) });
        int status = executeMethod(method);
        if (status == 200) {
            try {
                return mapper.readValue(method.getResponseBodyAsStream(), Authentication.class);
            } catch (IOException e) {
            }
        } else if (status == 403) {
            throw new ChangePasswordException();
        }
    } finally {
        method.releaseConnection();
    }
    return null;
}

From source file:com.markwatson.linkeddata.DBpediaLookupClient.java

public DBpediaLookupClient(String query) throws Exception {
    this.query = query;
    HttpClient client = new HttpClient();

    String query2 = query.replaceAll(" ", "+");
    HttpMethod method = new GetMethod(
            "http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=" + query2);
    try {// w w w .  j  a v  a 2 s . c  om
        client.executeMethod(method);
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.err.println("Http error connecting to lookup.dbpedia.org");
    } catch (IOException ioe) {
        System.err.println("Unable to connect to lookup.dbpedia.org");
    }
    method.releaseConnection();
}

From source file:com.wafersystems.util.HttpUtil.java

/**
 * URL?//from www . j ava2s . c o m
 * 
 * @param hClient   HttpClient
 * @param url      URL
 * 
 * @return
 * @throws Exception
 */
public static String openURL(HttpClient hClient, String url) throws Exception {
    HttpMethod method = null;
    try {
        //Get
        method = new GetMethod(url);
        // URL
        int result = hClient.executeMethod(method);
        //cookie?
        //getCookie(method.getURI().getHost(), method.getURI().getPort(), "/" , false , hClient.getState().getCookies());

        //???
        result = checkRedirect(method.getURI().getHost(), method.getURI().getPort(), hClient, method, result);

        if (result != HttpStatus.SC_OK)
            logger.error(method.getPath() + "" + method.getStatusLine().toString() + "\r\n"
                    + method.getResponseBodyAsString());

        return method.getResponseBodyAsString();
    } finally {
        method.releaseConnection();
    }
}

From source file:com.alta189.cyborg.commit.ShortUrlService.java

public static String shorten(String url, String keyword) {
    switch (service) {
    case BIT_LY:/*from w  ww. j a  v a  2  s .c om*/
        HttpClient httpclient = new HttpClient();
        HttpMethod method = new GetMethod("http://api.bit.ly/shorten");
        method.setQueryString(
                new NameValuePair[] { new NameValuePair("longUrl", url), new NameValuePair("version", "2.0.1"),
                        new NameValuePair("login", user), new NameValuePair("apiKey", apiKey),
                        new NameValuePair("format", "xml"), new NameValuePair("history", "1") });
        try {
            httpclient.executeMethod(method);
            String responseXml = method.getResponseBodyAsString();
            String retVal = null;
            if (responseXml != null) {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                StringReader st = new StringReader(responseXml);
                Document d = db.parse(new InputSource(st));
                NodeList nl = d.getElementsByTagName("shortUrl");
                if (nl != null) {
                    Node n = nl.item(0);
                    retVal = n.getTextContent();
                }
            }

            return retVal;
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return null;
    case SPOUT_IN:
        HttpClient client = new HttpClient();
        String result = null;
        client.getParams().setParameter("http.useragent", "Test Client");

        BufferedReader br = null;
        PostMethod pMethod = new PostMethod("http://spout.in/yourls-api.php");
        pMethod.addParameter("signature", apiKey);
        pMethod.addParameter("action", "shorturl");
        pMethod.addParameter("format", "simple");
        pMethod.addParameter("url", url);
        if (keyword != null) {
            pMethod.addParameter("keyword", keyword);
        }

        try {
            int returnCode = client.executeMethod(pMethod);

            if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
                System.err.println("The Post method is not implemented by this URI");
                pMethod.getResponseBodyAsString();
            } else {
                br = new BufferedReader(new InputStreamReader(pMethod.getResponseBodyAsStream()));
                String readLine;
                if (((readLine = br.readLine()) != null)) {
                    result = readLine;
                }
            }
        } catch (Exception e) {
            System.err.println(e);
        } finally {
            pMethod.releaseConnection();
            if (br != null) {
                try {
                    br.close();
                } catch (Exception fe) {
                    fe.printStackTrace();
                }
            }
        }
        return result;
    }
    return null;
}