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.braindrainpain.docker.httpsupport.HttpClientService.java

public JsonArray getJsonElementsFromUrl(String url, String memberName) {
    JsonArray result = null;/*from   w  w  w . ja v  a2s . co m*/
    try {
        GetMethod get = new GetMethod(url);
        if (httpClient.executeMethod(get) == HttpStatus.SC_OK) {
            String jsonString = get.getResponseBodyAsString();
            LOG.info("RECIEVED: " + jsonString);
            result = parseJson(jsonString, memberName);
            LOG.info("Build result: " + result);
        }
    } catch (IOException e) {
        // Wrap into a runtime. There is nothing useful to do here
        // when this happens.
        LOG.error("cannot fetch the tags from " + url);
        throw new RuntimeException("Cannot fetch the tags from " + url, e);
    }

    return result;
}

From source file:com.mikenimer.familydam.web.jobs.FacebookStatusJob.java

@Override
protected JobResult queryFacebook(Node facebookData, String username, String userPath, String nextUrl)
        throws RepositoryException, IOException, JSONException {
    String accessToken = facebookData.getProperty("accessToken").getString();
    String expiresIn = facebookData.getProperty("expiresIn").getString();
    String signedRequest = facebookData.getProperty("signedRequest").getString();

    String userId = "me";
    if (facebookData.hasProperty("userId")) {
        userId = facebookData.getProperty("userId").getString();
    }/* ww  w  .  j  a  v  a 2s .co  m*/

    String _url = nextUrl;
    if (nextUrl == null) {
        _url = "https://graph.facebook.com/" + userId + "/statuses?access_token=" + accessToken;
    }
    URL url = new URL(_url);

    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(_url);
    int statusCode = client.executeMethod(method);

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

    // Read the response body.
    String jsonStr = method.getResponseBodyAsString();
    return saveData(username, jsonStr, FACEBOOKPATH, "status");
}

From source file:com.buzzcoders.yasw.widgets.map.support.GMapUtils.java

/**
 * Returns the coordinates of the specified address.
 * /*from   w w w.j av a2  s.co  m*/
 * @param addressText the address to look
 * @return the latitude and longitude information
 */
public static LatLng getAddressCoordinates(String addressText) {
    LatLng coordinates = null;
    GetMethod locateAddressGET = null;
    HttpClient client = null;
    try {
        String addressUrlEncoded = URLEncoder.encode(addressText, "UTF-8");
        String locationFindURL = "http://maps.google.com/maps/api/geocode/json?sensor=false&address="
                + addressUrlEncoded;
        client = new HttpClient();
        locateAddressGET = new GetMethod(locationFindURL);
        int httpRetCode = client.executeMethod(locateAddressGET);
        if (httpRetCode == HttpStatus.SC_OK) {
            String responseBodyAsString = locateAddressGET.getResponseBodyAsString();
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            JsonNode location = jsonRoot.path("results").get(0).path("geometry").path("location");
            JsonNode lat = location.get("lat");
            JsonNode lng = location.get("lng");
            coordinates = new LatLng(lat.asDouble(), lng.asDouble());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (locateAddressGET != null)
            locateAddressGET.releaseConnection();
        if (client != null)
            client.getState().clear();
    }
    return coordinates;
}

From source file:com.tops.hotelmanager.util.CommonHttpClient.java

public static String executeGetRequest(String url, Map<String, String> map, Map<String, String> header,
        int timeOut) {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setSoTimeout(timeOut);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);
    StringBuilder sb = new StringBuilder(url);
    GetMethod get = null;//  ww w.ja v  a 2 s. co m
    try {
        if (map != null && map.size() > 0) {
            sb.append("?");
            int i = 0;
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (i == 0) {
                    sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                    i = 1;
                } else {
                    sb.append("&").append(entry.getKey()).append("=")
                            .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                }
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Requested URL : " + URLDecoder.decode(sb.toString(), "UTF-8"));
        }
        get = new GetMethod(sb.toString());
        if (header != null && header.size() > 0) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                get.addRequestHeader(entry.getKey(), entry.getValue());
            }
        }
        int i = client.executeMethod(get);
        if (i != -1) {
            String response = get.getResponseBodyAsString();
            /*
             * if (logger.isDebugEnabled()) { logger.debug("Response : " +
             * response); }
             */
            return response;
        }
    } catch (Exception e) {
        logger.error("HttpClient get method error url: " + url + ", Parameters: " + map, e);
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

    return "error~Request Failed";
}

From source file:exception.handler.configuration.ExceptionHandlerRedirectConfigTest.java

@Test
public void notHandlerConfiguration() {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(deploymentUrl + "/index.jsf");

    try {/*from   w  ww . j  a va 2  s.  c  om*/
        client.executeMethod(method);
        String message = method.getResponseBodyAsString();
        assertTrue(message.contains("Called the page /error_page"));

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.mikenimer.familydam.web.jobs.FacebookCheckinsJob.java

@Override
protected JobResult queryFacebook(Node facebookData, String username, String userPath, String nextUrl)
        throws RepositoryException, IOException, JSONException {
    String accessToken = facebookData.getProperty("accessToken").getString();
    String expiresIn = facebookData.getProperty("expiresIn").getString();
    String signedRequest = facebookData.getProperty("signedRequest").getString();

    String userId = "me";
    if (facebookData.hasProperty("userId")) {
        userId = facebookData.getProperty("userId").getString();
    }//from   www.  j av  a 2  s.  com

    String _url = nextUrl;
    if (nextUrl == null) {
        _url = "https://graph.facebook.com/" + userId + "/checkins?access_token=" + accessToken;
    }
    URL url = new URL(_url);

    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(_url);
    int statusCode = client.executeMethod(method);

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

    // Read the response body.
    String jsonStr = method.getResponseBodyAsString();
    return saveData(username, jsonStr, FACEBOOKPATH, "checkin");
}

From source file:com.dragoniade.deviantart.deviation.SearchRss.java

public List<Deviation> search(ProgressDialog progress, Collection collection) {
    if (user == null) {
        throw new IllegalStateException("You must set the user before searching.");
    }/*from   w  w  w.  j a v a  2s. co m*/
    if (search == null) {
        throw new IllegalStateException("You must set the search type before searching.");
    }
    if (total < 0) {
        progress.setText("Fetching total (0)");
        total = retrieveTotal(progress, collection);
        progress.setText("Total: " + total);
    }

    String searchQuery = search.getSearch().replace("%username%", user);
    String queryString = "http://backend.deviantart.com/rss.xml?q=" + searchQuery
            + (collection == null ? "" : "/" + collection.getId()) + "&type=deviation&offset=" + offset;
    GetMethod method = new GetMethod(queryString);
    List<Deviation> results = new ArrayList<Deviation>(OFFSET);
    try {
        int sc = -1;
        do {
            sc = client.executeMethod(method);
            if (sc != 200) {
                LoggableException ex = new LoggableException(method.getResponseBodyAsString());
                Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ex);

                int res = DialogHelper.showConfirmDialog(owner,
                        "An error has occured when contacting deviantART : error " + sc + ". Try again?",
                        "Continue?", JOptionPane.YES_NO_OPTION);
                if (res == JOptionPane.NO_OPTION) {
                    return null;
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
            }
        } while (sc != 200);

        XmlToolkit toolkit = XmlToolkit.getInstance();

        Element responses = toolkit.parseDocument(method.getResponseBodyAsStream());
        method.releaseConnection();

        HashMap<String, String> prefixes = new HashMap<String, String>();
        prefixes.put("media", responses.getOwnerDocument().lookupNamespaceURI("media"));
        NamespaceContext context = toolkit.getNamespaceContext(prefixes);

        List<?> deviations = toolkit.getMultipleNodes(responses, "channel/item");
        if (deviations.size() == 0) {
            return results;
        }

        for (Object obj : deviations) {
            Element deviation = (Element) obj;

            Deviation da = new Deviation();
            da.setId(getId(toolkit.getNodeAsString(deviation, "guid")));
            da.setArtist(toolkit.getNodeAsString(deviation, "media:credit", context));
            da.setCategory(toolkit.getNodeAsString(deviation, "media:category", context));
            da.setTitle(toolkit.getNodeAsString(deviation, "media:title", context));
            da.setUrl(toolkit.getNodeAsString(deviation, "link"));
            da.setTimestamp(parseDate(toolkit.getNodeAsString(deviation, "pubDate")));
            da.setMature(!"nonadult".equals(toolkit.getNodeAsString(deviation, "media:rating", context)));
            da.setCollection(collection);

            Element documentNode = (Element) toolkit.getSingleNode(deviation,
                    "media:content[@medium='document']", context);
            Element imageNode = (Element) toolkit.getSingleNode(deviation, "media:content[@medium='image']",
                    context);
            Element videoNode = (Element) toolkit.getSingleNode(deviation, "media:content[@medium='video']",
                    context);

            if (imageNode != null) {
                String content = imageNode.getAttribute("url");
                String filename = Deviation.extractFilename(content);
                da.setImageDownloadUrl(content);
                da.setImageFilename(filename);

                da.setResolution(imageNode.getAttribute("width") + "x" + imageNode.getAttribute("height"));
            }

            if (documentNode != null) {
                String content = documentNode.getAttribute("url");
                String filename = Deviation.extractFilename(content);
                da.setDocumentDownloadUrl(content);
                da.setDocumentFilename(filename);
            }

            if (videoNode != null) {
                String content = videoNode.getAttribute("url");
                if (!content.endsWith("/")) {
                    content = content + "/";
                }
                String filename = Deviation.extractFilename(content);
                da.setDocumentDownloadUrl(content);
                da.setDocumentFilename(filename);
            }

            results.add(da);
        }
        offset = offset + deviations.size();
        return results;
    } catch (HttpException e) {
        DialogHelper.showMessageDialog(owner, "Error contacting deviantART : " + e.getMessage() + ".", "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    } catch (IOException e) {
        DialogHelper.showMessageDialog(owner, "Error contacting deviantART : " + e.getMessage() + ".", "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    }
}

From source file:edu.harvard.iq.dvn.core.web.servlet.ICPSRproxyServlet.java

public void service(HttpServletRequest req, HttpServletResponse res) {

    String icpsrId = req.getParameter("icpsrId");

    if (icpsrId != null) {
        Base64 b64 = new Base64();

        byte[] bytesDecoded = b64.decode(icpsrId.getBytes());

        String icpsrURLdecoded = new String(bytesDecoded);

        if (icpsrURLdecoded.startsWith("http")) {

            GetMethod method = null;//from w  ww  .  j  a v  a  2s .c o m
            int status = 200;

            try {
                method = new GetMethod(icpsrURLdecoded);
                status = getClient().executeMethod(method);
            } catch (IOException ex) {
                // return 404 
                // and generate a FILE NOT FOUND message

                createErrorResponse404(res);
                if (method != null) {
                    method.releaseConnection();
                }
                return;
            }

            if (status == 403) {
                // generate an HTML-ized response with a correct 
                // 403/FORBIDDEN code   

                createErrorResponse403(res);
                if (method != null) {
                    method.releaseConnection();
                }
                return;
            }

            if (status == 404) {
                // generate an HTML-ized response with a correct 
                // 404/FILE NOT FOUND code   

                createErrorResponse404(res);
                if (method != null) {
                    method.releaseConnection();
                }
                return;
            }

            // a generic response for all other failure cases:

            if (status != 200) {
                createErrorResponseGeneric(res, status,
                        (method.getStatusLine() != null) ? method.getStatusLine().toString()
                                : "Unknown HTTP Error");
                if (method != null) {
                    method.releaseConnection();
                }
                return;
            }

            try {
                // recycle all the incoming headers 
                for (int i = 0; i < method.getResponseHeaders().length; i++) {
                    res.setHeader(method.getResponseHeaders()[i].getName(),
                            method.getResponseHeaders()[i].getValue());
                }

                // send the incoming HTTP stream as the response body

                InputStream in = method.getResponseBodyAsStream();
                OutputStream out = res.getOutputStream();

                int i = in.read();
                while (i != -1) {
                    out.write(i);
                    i = in.read();
                }
                in.close();
                out.close();

            } catch (IOException ex) {
                ex.printStackTrace();
            }

            method.releaseConnection();
        } else {
            createErrorResponse404(res);
            return;
        }

    } else {
        createErrorResponse404(res);
        return;
    }
}

From source file:com.atlassian.theplugin.util.InfoServer.java

public static void reportOptInOptOut(final long uid, final Boolean optIn) {
    Thread t = new Thread(new Runnable() {
        public void run() {
            String getMethodUrl = getServiceUrl(false);
            HttpClient client;/*from   w w  w.j a v  a  2  s.  com*/
            try {
                client = HttpClientFactory.getClient();
                getMethodUrl += "?uid=" + uid + "&userOptedIn=" + (optIn == null || optIn ? 1 : 0);
                GetMethod method = new GetMethod(getMethodUrl);
                client.executeMethod(method);
                method.getResponseBodyAsStream(); // ignore response
            } catch (InvalidCredentialsException e) {
                //                    LoggerImpl.getInstance().info(e.getMessage());
            } catch (HttpProxySettingsException e) {
                LoggerImpl.getInstance().error(e);
            } catch (IOException e) {
                LoggerImpl.getInstance().error(e);
            }
        }
    });
    t.start();
}

From source file:com.denimgroup.threadfix.importer.impl.remoteprovider.utils.RemoteProviderHttpUtilsImpl.java

@Override
public HttpResponse getUrlWithConfigurer(String url, RequestConfigurer configurer) {
    assert url != null;
    assert configurer != null;

    GetMethod get = new GetMethod(url);

    get.setRequestHeader("Content-type", "text/xml; charset=UTF-8");

    configurer.configure(get);//  w ww  .  j av  a  2s. co m

    HttpClient client = getConfiguredHttpClient(classInstance);

    int status = -1;

    try {
        status = client.executeMethod(get);

        if (status != 200) {
            LOG.warn("Status wasn't 200, it was " + status);
            return HttpResponse.failure(status, get.getResponseBodyAsStream());
        } else {
            return HttpResponse.success(status, get.getResponseBodyAsStream());
        }

    } catch (IOException e) {
        LOG.error("Encountered IOException while making request in " + classInstance.getName() + ". "
                + e.toString());
        throw new RestException(e, e.toString());
    }
}