List of usage examples for org.apache.http.client.methods RequestBuilder get
public static RequestBuilder get()
From source file:edu.mit.scratch.ScratchUser.java
public List<ScratchProject> getFavoriteProjects(final int limit, final int offset) throws ScratchUserException { final List<ScratchProject> ids = new ArrayList<>(); try {/*from www . j a v a 2s.com*/ final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); lang.setPath("/"); lang.setDomain(".scratch.mit.edu"); cookieStore.addCookie(lang); cookieStore.addCookie(debug); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest update = RequestBuilder.get() .setUri("https://api.scratch.mit.edu/users/" + this.getUsername() + "/favorites?limit=" + limit + "&offset=" + offset) .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") .addHeader("Referer", "https://scratch.mit.edu/users/" + this.getUsername() + "/") .addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate, sdch") .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json") .addHeader("X-Requested-With", "XMLHttpRequest").build(); try { resp = httpClient.execute(update); } catch (final IOException e) { e.printStackTrace(); throw new ScratchUserException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchUserException(); } final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); final JSONArray jsonOBJ2 = new JSONArray(result.toString().trim()); for (int i = 0; i < jsonOBJ2.length(); i++) { final JSONObject jsonOBJ = jsonOBJ2.getJSONObject(i); final Iterator<?> keys = jsonOBJ.keys(); while (keys.hasNext()) { final String key = "" + keys.next(); final Object o = jsonOBJ.get(key); final String val = "" + o; if (key.equalsIgnoreCase("id")) ids.add(new ScratchProject(Integer.parseInt(val))); } } return ids; } catch (final UnsupportedEncodingException e) { e.printStackTrace(); throw new ScratchUserException(); } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } }
From source file:fi.okm.mpass.shibboleth.attribute.resolver.dc.impl.RestDataConnector.java
/** * Fetch school name from external API.//w ww . ja va2 s . c o m * @param clientBuilder The HTTP client builder. * @param id The school id whose information is fetched. * @param baseUrl The base URL for the external API. It is appended with the ID of the school. * @return The name of the school. */ public static synchronized String getSchoolName(final HttpClientBuilder clientBuilder, final String id, final String baseUrl) { final Logger log = LoggerFactory.getLogger(RestDataConnector.class); if (StringSupport.trimOrNull(id) == null || !StringUtils.isNumeric(id) || id.length() > 6) { return null; } final HttpResponse response; try { final HttpUriRequest get = RequestBuilder.get().setUri(baseUrl + id).build(); response = clientBuilder.buildClient().execute(get); } catch (Exception e) { log.error("Could not get school information with id {}", id, e); return null; } if (response == null) { log.error("Could not get school information with id {}", id); return null; } final String output; try { output = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (ParseException | IOException e) { log.error("Could not parse school information response with id {}", id, e); return null; } finally { EntityUtils.consumeQuietly(response.getEntity()); } log.trace("Fetched the following response body: {}", output); final Gson gson = new Gson(); try { final OpintopolkuOppilaitosDTO[] oResponse = gson.fromJson(output, OpintopolkuOppilaitosDTO[].class); if (oResponse.length == 1 && oResponse[0].getMetadata() != null && oResponse[0].getMetadata().length == 1) { log.debug("Successfully fetched name for id {}", id); return oResponse[0].getMetadata()[0].getName(); } } catch (JsonSyntaxException | IllegalStateException e) { log.warn("Could not parse the response", e); log.debug("The unparseable response was {}", output); } log.warn("Could not find name for id {}", id); return null; }
From source file:org.bonitasoft.connectors.rest.RESTConnector.java
/** * Generate a request builder based on the given method * /*from www. jav a 2s . co m*/ * @param method The method * @return The request builder */ private RequestBuilder getRequestBuilderFromMethod(final HTTPMethod method) { switch (method) { case GET: return RequestBuilder.get(); case POST: return RequestBuilder.post(); case PUT: return RequestBuilder.put(); case DELETE: return RequestBuilder.delete(); default: throw new IllegalStateException( "Impossible to get the RequestBuilder from the \"" + method.name() + "\" name."); } }
From source file:org.dasein.cloud.azure.compute.vm.AzureVM.java
private boolean canDeleteDeployment(String serviceName, String deploymentName, String roleName) throws CloudException, InternalException { String deploymentUri = String.format(DEPLOYMENT_RESOURCE, getProvider().getContext().getCloud().getEndpoint(), getProvider().getContext().getAccountNumber(), serviceName, deploymentName); DeploymentModel deploymentModel = new DaseinRequest(getProvider(), getProvider().getAzureClientBuilder(), RequestBuilder.get().addHeader("x-ms-version", "2014-05-01").setUri(deploymentUri).build()) .withXmlProcessor(DeploymentModel.class).execute(); if (deploymentModel.getRoles() == null) return true; if (deploymentModel.getRoles().size() == 1 && deploymentModel.getRoles().get(0).getRoleName().equalsIgnoreCase(roleName)) return true; return false; }
From source file:nl.opengeogroep.safetymaps.routing.service.OpenRouteService.java
@Override public RoutingResult getRoute(RoutingRequest request) throws RoutingException { RoutingResult result;//from ww w . j a v a 2 s. com try { CoordinateReferenceSystem crs = CRS.decode("epsg:28992"); CoordinateReferenceSystem serviceCrs = CRS.decode("epsg:4326"); MathTransform transform = CRS.findMathTransform(crs, serviceCrs, true); GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); Coordinate coord = new Coordinate(request.getFromX(), request.getFromY()); Point from = geometryFactory.createPoint(coord); coord = new Coordinate(request.getToX(), request.getToY()); Point to = geometryFactory.createPoint(coord); Point fromTransformed = (Point) JTS.transform(from, transform); Point toTransformed = (Point) JTS.transform(to, transform); log.info("Reprojected destination point to service CRS: " + toTransformed); try (CloseableHttpClient client = getClient()) { HttpUriRequest get = RequestBuilder.get().setUri("https://api.openrouteservice.org/directions") .addHeader("Accept", "text/json; charset=utf-8").addParameter("api_key", apiKey) .addParameter("coordinates", fromTransformed.getY() + "," + fromTransformed.getX() + "|" + toTransformed.getY() + "," + toTransformed.getX()) .addParameter("profile", profile).addParameter("preference", preference) .addParameter("format", "geojson").addParameter("language", "nl") //.addParameter("instructions", "false") .addParameter("elevation", "false").addParameter("extra_info", "").build(); log.info("GET > " + get.getRequestLine()); String response = client.execute(get, new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse hr) { log.trace("< " + hr.getStatusLine()); String entity = null; try { entity = IOUtils.toString(hr.getEntity().getContent(), "UTF-8"); } catch (IOException e) { } if (hr.getStatusLine().getStatusCode() != SC_OK) { log.error("HTTP error: " + hr.getStatusLine() + ", " + entity); } log.trace("< entity: " + entity); return entity; } }); if (response != null) { JSONObject res = new JSONObject(response); log.info("JSON response: " + res.toString(4)); result = new RoutingResult(true, res); result.setDistance(calculateDistance(res)); result.setRoute(res); } else { result = new RoutingResult(false, "Error calculating route: null response", null); } } } catch (Exception e) { log.error("Error calculating route", e); result = new RoutingResult(false, "Error calculating route: " + e.getMessage(), e); } return result; }