@Override public void activateBrowserfeatures(final Upload upload) throws UnirestException { // Create a local instance of cookie store // Populate cookies if needed final CookieStore cookieStore = new BasicCookieStore(); for (final PersistentCookieStore.SerializableCookie serializableCookie : upload.getAccount().getSerializeableCookies()) { final BasicClientCookie cookie = new BasicClientCookie( serializableCookie.getCookie().getName(), serializableCookie.getCookie().getValue()); cookie.setDomain(serializableCookie.getCookie().getDomain()); cookieStore.addCookie(cookie); } final HttpClient client = HttpClientBuilder.create().useSystemProperties().setDefaultCookieStore(cookieStore).build(); Unirest.setHttpClient(client); final HttpResponse<String> response = Unirest.get(String.format(VIDEO_EDIT_URL, upload.getVideoid())).asString(); changeMetadata(response.getBody(), upload); final RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(600000).build(); Unirest.setHttpClient(HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).build()); }
@SuppressWarnings("unchecked") public Map<ProjectVersionRef, String> translateVersions(List<ProjectVersionRef> projects) { // Execute request to get translated versions HttpResponse<Map> r; try { r = Unirest.post(this.endpointUrl) .header("accept", "application/json") .header("Content-Type", "application/json") .body(projects) .asObject(Map.class); } catch (UnirestException e) { throw new RestException( String.format( "Request to server '%s' failed. Exception message: %s", this.endpointUrl, e.getMessage())); } // Handle some corner cases (5xx, 4xx) if (r.getStatus() / 100 == 5) { throw new ServerException( String.format( "Server at '%s' failed to translate versions. HTTP status code %s.", this.endpointUrl, r.getStatus())); } else if (r.getStatus() / 100 == 4) { throw new ClientException( String.format( "Server at '%s' could not translate versions. HTTP status code %s.", this.endpointUrl, r.getStatus())); } return r.getBody(); }
/** * <code>initiate</code> starts the operations of this system handler. All excecution code for the * plugins is expected to begin at this point. * * @throws UnRetriableException */ @Override public void initiate() throws UnRetriableException { // Initiate the session reset manager. SessionResetManager sessionResetManager = new SessionResetManager(); sessionResetManager.setWorker(this); sessionResetManager.setDatastore(this.getDatastore()); setSessionResetManager(sessionResetManager); String igniteCacheName = "dumbTester"; CacheConfiguration clCfg = new CacheConfiguration(); clCfg.setName(igniteCacheName); clCfg.setAtomicityMode(CacheAtomicityMode.ATOMIC); clCfg.setCacheMode(CacheMode.PARTITIONED); clCfg.setMemoryMode(CacheMemoryMode.ONHEAP_TIERED); LruEvictionPolicy lruEvictionPolicy = new LruEvictionPolicy(5170000); clCfg.setEvictionPolicy(lruEvictionPolicy); clCfg.setSwapEnabled(true); // if(subscriptions instanceof IgniteCache) { // subscriptions = getIgnite().createCache(clCfg); // } // Initiate unirest properties. Unirest.setTimeouts(5000, 5000); }
private void changeMetadata(final String content, final Upload upload) { final Map<String, Object> params = new HashMap<>(METADATA_PARAMS_SIZE); params.putAll(getMetadataSocial(upload)); params.putAll(getMetadataMonetization(content, upload)); params.putAll(getMetadataMetadata(upload)); params.putAll(getMetadataPermissions(upload)); System.out.println(Joiner.on(MODIFIED_SEPERATOR).skipNulls().join(params.keySet())); params.put("modified_fields", Joiner.on(MODIFIED_SEPERATOR).skipNulls().join(params.keySet())); params.put("creator_share_feeds", "yes"); final String token = extractor(content, "var session_token = \"", "\""); params.put("session_token", token); params.put("action_edit_video", "1"); try { final HttpResponse<String> response = Unirest.post( String.format( "https://www.youtube.com/metadata_ajax?video_id=%s", upload.getVideoid())) .fields(params) .asString(); LOGGER.info(response.getBody()); } catch (final Exception e) { LOGGER.warn("Metadata not set", e); } }
@Override public HttpResponse<JsonNode> post(File file, Hashtable<String, Boolean> options) throws UnirestException { // TODO Auto-generated method stub String s = ""; imageProc = new ImageProc(file.getAbsolutePath()); if (options.get("Gender")) { s = s.concat("Gender"); } if ((options.get("Glasses")) || (options.get("Sunglasses"))) { if (s.equals("")) s = s.concat("Glasses"); else s = s.concat(", Glasses"); } if (options.get("Smile")) { if (s.equals("")) s = s.concat("Smiling"); else s = s.concat(", Smiling"); } if (s.equals("")) { s = "none"; } return Unirest.post( "https://face.p.mashape.com/faces/detect?api_key=771b5991a5ff4ce1a7cfcef2e1d91ae5&api_secret=cfc895f2c40e475eb1032be25b63f969") .header("X-Mashape-Key", "kCKZDyhuAxmsh2l2E7GXVfOLFe9hp1w77PbjsnmUiFR69J94RG") .field("attributes", s) .field("detector", "Aggressive") .field("files", file) .asJson(); }
protected org.json.JSONArray getRestResponse(@Context UriInfo uriInfo, String category) throws UnirestException { return Unirest.post(uriInfo.getAbsolutePathBuilder().path(NewsGetter.class) + category) .asJson() .getBody() .getArray(); }
public String create() { try { JsonObject gistJson = new JsonObject(); gistJson.addProperty("description", this.getDescription()); gistJson.addProperty("public", this.isPublic()); JsonObject filesJson = new JsonObject(); for (int i = 0; i < getFiles().length; i++) { GistFile gistFile = getFiles()[i]; JsonObject file = new JsonObject(); file.addProperty("content", gistFile.getContent()); String name = gistFile.getFileName(); filesJson.add( (name == null || name.isEmpty() ? "" : name + "-") + date.replace(' ', '_'), file); } gistJson.add("files", filesJson); HttpResponse<JsonNode> response = Unirest.post(GitHub.GISTS_API_URL) .header( "authorization", "token " + Nexus.getInstance().getGitHubConfig().getNexusGitHubApiKey()) .header("accept", "application/json") .header("content-type", "application/json; charset=utf-8") .body(gistJson.toString()) .asJson(); return response.getBody().getObject().getString("html_url"); } catch (UnirestException e) { throw new GistException("Failed to Gist!", e); } }
@SuppressWarnings("unchecked") public String postJSON(String url, String jsonData, Map<String, String> headers) throws URISyntaxException, ParseException { HttpResponse<JsonNode> httpResponse = null; if (!validatorUtil.isHttpURLValid(url)) { throw new URISyntaxException(url, "The URL is not absolute"); } if (!validatorUtil.isJSONValid(jsonData)) { throw new ParseException(ParseException.ERROR_UNEXPECTED_TOKEN); } try { httpResponse = Unirest.post(url).headers(headers).body(jsonData).asJson(); } catch (UnirestException e) { LOGGER.error("Exception occured while making post call"); JSONObject errorObject = new JSONObject(); errorObject.put("status", "500"); errorObject.put("message", e.getLocalizedMessage()); return errorObject.toJSONString(); } return httpResponse.getBody().toString(); }
public static void init() { Unirest.setObjectMapper( new ObjectMapper() { private com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); { mapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); } public <T> T readValue(String value, Class<T> valueType) { try { return mapper.readValue(value, valueType); } catch (IOException e) { throw new RuntimeException(e); } } public String writeValue(Object o) { try { return mapper.writeValueAsString(o); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); }
@Override public Message sendFile(File file, Message message) { checkVerification(); if (!checkPermission(getJDA().getSelfInfo(), Permission.MESSAGE_WRITE)) throw new PermissionException(Permission.MESSAGE_WRITE); if (!checkPermission(getJDA().getSelfInfo(), Permission.MESSAGE_ATTACH_FILES)) throw new PermissionException(Permission.MESSAGE_ATTACH_FILES); if (file == null || !file.exists() || !file.canRead()) throw new IllegalArgumentException( "Provided file is either null, doesn't exist or is not readable!"); if (file.length() > 8 << 20) // 8MB throw new IllegalArgumentException("File is to big! Max file-size is 8MB"); JDAImpl api = (JDAImpl) getJDA(); try { MultipartBody body = Unirest.post(Requester.DISCORD_API_PREFIX + "channels/" + getId() + "/messages") .header("authorization", getJDA().getAuthToken()) .header("user-agent", Requester.USER_AGENT) .field("file", file); if (message != null) body.field("content", message.getRawContent()).field("tts", message.isTTS()); String dbg = String.format( "Requesting %s -> %s\n\tPayload: file: %s, message: %s, tts: %s\n\tResponse: ", body.getHttpRequest().getHttpMethod().name(), body.getHttpRequest().getUrl(), file.getAbsolutePath(), message == null ? "null" : message.getRawContent(), message == null ? "N/A" : message.isTTS()); HttpResponse<JsonNode> response = body.asJson(); Requester.LOG.trace(dbg + body); try { int status = response.getStatus(); if (status >= 200 && status < 300) { return new EntityBuilder(api).createMessage(response.getBody().getObject()); } else if (response.getStatus() == 429) { long retryAfter = response.getBody().getObject().getLong("retry_after"); api.setMessageTimeout(guild.getId(), retryAfter); throw new RateLimitedException(retryAfter); } else { throw new RuntimeException( "An unknown status code was returned when attempting to upload file. Status: " + status + " JSON: " + response.getBody().toString()); } } catch (JSONException e) { Requester.LOG.fatal("Following json caused an exception: " + response.getBody().toString()); Requester.LOG.log(e); } } catch (UnirestException e) { Requester.LOG.log(e); } return null; }
protected org.json.JSONArray getRestResponse(String category) throws UnirestException { return Unirest.get("http://localhost:8080/RssFeeder/news/" + category) .asJson() .getBody() .getArray(); }
// Start up the server, listening on port 8000 at the relative path '/events' public static void main(String[] args) { // Set headers common to every Connect API request Unirest.setDefaultHeader("Authorization", "Bearer " + _accessToken); Unirest.setDefaultHeader("Content-Type", "application/json"); Unirest.setDefaultHeader("Accept", "application/json"); try { HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/events", new EventsHandler()); server.setExecutor(null); server.start(); } catch (IOException e) { System.out.println("Server startup failed. Exiting."); System.exit(1); } }
/** * <code>terminate</code> halts excecution of this plugin. This provides a clean way to exit /stop * operations of this particular plugin. */ @Override public void terminate() { // Shutdown unirest. try { Unirest.shutdown(); } catch (IOException e) { log.warn(" terminate : problem closing unirest", e); } }
public static HttpResponse<JsonNode> get(String url) { HttpResponse<JsonNode> response = null; try { response = Unirest.get(url).asJson(); } catch (UnirestException e) { LOGGER.warning(Messages.DockerRegistryHelper_InaccessibleUrl()); e.printStackTrace(); } return response; }
public void destroy() throws IOException { try { Unirest.delete("https://mktmp.io/api/v1/i/" + env.id) .header("accept", "application/json") .header("X-Auth-Token", env.token) .asJson(); } catch (UnirestException ex) { throw new IOException("Failed to terminate instance " + env.id, ex); } }
@Override public void exec(Sys sys, User user, Group group, String used, String[] args, Message message) { if (args.length >= 2) { String from = args[0], to = args[1]; try { JSONObject res = Unirest.get( String.format( "http://www.distance24.org/route.json?stops=%s", URLEncoder.encode(from + "|" + to, "UTF-8"))) .asJson() .getBody() .getObject(); JSONArray arr = res.getJSONArray("stops"); boolean fromValid = true, toValid = true; if (arr.getJSONObject(0).getString("type").equalsIgnoreCase("Invalid")) { fromValid = false; } else { from = arr.getJSONObject(0).getString("city") + (arr.getJSONObject(0).has("region") ? ", " + arr.getJSONObject(0).getString("region") : ""); } if (arr.getJSONObject(1).getString("type").equalsIgnoreCase("Invalid")) { toValid = false; } else { to = arr.getJSONObject(1).getString("city") + ", " + (arr.getJSONObject(1).has("region") ? ", " + arr.getJSONObject(1).getString("region") : ""); } if (fromValid && toValid) { group.sendMessage( sys.message() .escaped("Distance (%s => %s): %s km", from, to, res.getDouble("distance"))); } else { String disp = ""; if (!fromValid) { disp += from; } if (!toValid) { disp += (disp.isEmpty() ? "" : ", ") + to; } group.sendMessage(sys.message().escaped("[Distance] Invalid city name(s): " + disp)); } } catch (IOException | UnirestException e) { e.printStackTrace(); } } else { this.sendUsage(sys, user, group); } }
public static int getResponseCode(String url) { HttpResponse<JsonNode> response; int responseCode = 0; try { response = Unirest.get(url).asJson(); responseCode = response.getStatus(); } catch (UnirestException e) { // NO-OP } return responseCode; }
// auth.test private JSONObject getUser(String token) throws UnirestException { HttpResponse<JsonNode> response2 = Unirest.post("https://slack.com/api/auth.test") .header("cache-control", "no-cache") .header("postman-token", "8fde8d56-5dba-fa69-6c1e-81c34bf24e78") .header("content-type", "application/x-www-form-urlencoded") .body("token=" + token) .asJson(); JSONObject userdata = response2.getBody().getObject(); return userdata; }
private JSONObject getFreegeoip(HttpServletRequest request) { try { String dirIp = extractIP(request); HttpResponse<JsonNode> response = Unirest.get("http://freegeoip.net/json/" + dirIp).asJson(); return response.getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); return null; } }
/** * Test that searches' verbs/methods work as expected. Because our usual {@link Client} object * only creates well-formed requests, we use Unirest, a simple REST client API, to connect to the * server. * * @param fullUrl the URL to test */ private void tryMalformedSearchPayloads(final String fullUrl) throws UnirestException { // send some malformed requests and expect status == HTTP_BAD_REQUEST final String[] requestBodies = {"", "JSON", "<xml/>", "{", "}", "{\"bad:\"", "{]"}; for (String datum : requestBodies) { assertThat( Unirest.post(fullUrl) .header("Content-type", "application/json") .body(datum) .asBinary() // make the request; we don't really care about the format .getStatus()) .isEqualTo(HttpURLConnection.HTTP_BAD_REQUEST); } }
@RequestMapping(value = "/rec/rec", method = RequestMethod.GET) public ResponseEntity<ArrayList<String>> recomendaciones( @RequestParam("url") String url, @RequestParam(value = "custom", required = false) String custom, @RequestParam(value = "expire", required = false) String expireDate, @RequestParam(value = "hasToken", required = false) String hasToken, HttpServletRequest request) { UrlValidator urlValidator = new UrlValidator(new String[] {"http", "https"}); /* * Check if url comes through http or https */ if (urlValidator.isValid(url)) { /* * Hash of URL or custom */ String id; if (!custom.equals("")) { id = custom; if (shortURLRepository.findByHash(id) == null) { System.out.println("1"); return new ResponseEntity<>(HttpStatus.CREATED); } else { System.out.println("2"); try { HttpResponse<JsonNode> response = Unirest.get("https://wordsapiv1.p.mashape.com/words/" + id + "/synonyms") .header("X-Mashape-Key", "VLzNEVr9zQmsh0gOlqs6wudMxDo1p1vCnjEjsnjNBhOCFeqLxr") .header("Accept", "application/json") .asJson(); ObjectMapper map = new ObjectMapper(); Synonym sin = map.readValue(response.getBody().toString(), Synonym.class); return new ResponseEntity<>(sin.getSynonyms(), HttpStatus.BAD_REQUEST); } catch (Exception e) { /* * Caso en el que la id seleccionada esta cogida y la * API no da alternativas */ return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } } else { return new ResponseEntity<>(HttpStatus.OK); } } else { System.out.println("3"); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }
public void onCommandMessageReceived(CommandMessageReceivedEvent event) { if (event.getCommand().equals("get")) { event .getChat() .sendMessage( SendableChatAction.builder().chatAction(ChatAction.UPLOADING_PHOTO).build(), ImageBot.bot); HttpResponse<JsonNode> response = null; try { response = Unirest.get(url + event.getArgsString().replace(" ", "+")).asJson(); } catch (UnirestException e) { e.printStackTrace(); } if (response.getBody().getObject().has("error")) { event .getChat() .sendMessage( "The Google API returned an error - Bot probably got ratelimited!", ImageBot.bot); System.out.println("Google API returned error: " + response.getBody()); return; } JSONArray array = response.getBody().getObject().getJSONArray("items"); if (array.length() == 0) { event.getChat().sendMessage("No images found!", ImageBot.bot); return; } JSONObject image = array.getJSONObject(ThreadLocalRandom.current().nextInt(array.length())); URL url; try { url = new URL(image.getString("link")); } catch (MalformedURLException e) { e.printStackTrace(); event.getChat().sendMessage("Something went wrong while getting the image!", ImageBot.bot); return; } System.out.println("Uploading photo: " + url); event .getChat() .sendMessage( SendablePhotoMessage.builder() .photo(new InputFile(url)) .replyTo(event.getMessage()) .build(), ImageBot.bot); System.out.println("Photo uploaded: " + url); } }
// @Test(groups = "mainPage") public void _01_Test() throws InterruptedException, IOException, UnirestException { HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .queryString("apiKey", "123") .field("parameter", "value") .field("foo", "bar") .asJson(); System.out.println("----------------------------"); System.out.println(jsonResponse); System.out.println("----------------------------"); Thread.sleep(1000); }
public String hello(Request request, Response response) { String token = readToken(request); HttpResponse<Car[]> carHttpResponse; try { carHttpResponse = Unirest.get("https://localhost:8099/cars") .header("Accept", "application/json") .header("Authorization", "Bearer " + token) .asObject(Car[].class); } catch (UnirestException e) { throw new RuntimeException(e); } Car[] cars = carHttpResponse.getBody(); List<String> carNames = Arrays.stream(cars).map(Car::getName).collect(toList()); return "We have these cars available: " + carNames; }
public static synchronized void sendUpdate(Transfer trans, String gameid) { lamport.Add(); try { Transaction transaction = new Transaction(trans, lamport.getTime()); transfers.add(trans); transactions.add(transaction); String tmp = gson.toJson(trans); Unirest.post(replication + "/sync/" + gameid) .header("Content-Type", "application/json") .body(tmp) .asString(); } catch (UnirestException e) { System.out.println("Konnte Dienste nicht synchronisieren."); e.printStackTrace(); } }
@SuppressWarnings("unchecked") public String getJSON(String url, Map<String, Object> queryParams) throws URISyntaxException { HttpResponse<JsonNode> httpResponse = null; if (!validatorUtil.isHttpURLValid(url)) { throw new URISyntaxException(url, "The URL is not absolute"); } try { httpResponse = Unirest.get(url).queryString(queryParams).asJson(); } catch (UnirestException e) { LOGGER.error("Exception occured while making get call"); JSONObject errorObject = new JSONObject(); errorObject.put("status", "500"); errorObject.put("message", e.getLocalizedMessage()); return errorObject.toJSONString(); } return httpResponse.getBody().toString(); }
// Handles all incoming webhook notifications public void handle(HttpExchange t) throws IOException { System.out.println("Request received"); // Reject non-POST requests if (!t.getRequestMethod().equals("POST")) { t.sendResponseHeaders(405, 0); t.getResponseBody().close(); } Headers requestHeaders = t.getRequestHeaders(); String callbackSignature = requestHeaders.get("X-square-signature").get(0); String callbackBody = IOUtils.toString(t.getRequestBody(), (String) null); if (!isValidCallback(callbackBody, callbackSignature)) { System.out.println("Webhook event with invalid signature detected!"); t.sendResponseHeaders(200, 0); t.getResponseBody().close(); return; } JSONObject requestBody = new JSONObject(callbackBody); if (requestBody.has("event_type") && requestBody.getString("event_type").equals("PAYMENT_UPDATED")) { // Get the ID of the updated payment String paymentId = requestBody.getString("entity_id"); // Get the ID of the payment's associated location String locationId = requestBody.getString("location_id"); HttpResponse<JsonNode> response; try { response = Unirest.get(_connectHost + "/v1/" + locationId + "/payments/" + paymentId).asJson(); } catch (UnirestException e) { System.out.println("Failed to retrieve payment details"); return; } System.out.println(response.getBody().getObject()); } t.sendResponseHeaders(200, 0); t.getResponseBody().close(); }
// @Test(groups = "mainPage") public void _02_Test() throws InterruptedException, IOException, UnirestException { HttpResponse<JsonNode> jsonResponse = Unirest.post("https://my.15five.com/mobile/login") .header("HTTP_USER_AGENT", "15Five/APItest") .queryString("debug_api", "1") .field("password", "qwerty") .field("email", "*****@*****.**") .asJson(); System.out.println("----------------------------"); System.out.println(jsonResponse.getBody()); System.out.println(jsonResponse.getStatus()); System.out.println(jsonResponse.getBody().getObject().get("result")); System.out.println(jsonResponse.getBody().getObject().get("last_name")); System.out.println("----------------------------"); Thread.sleep(1000); }
// oauth.access private JSONObject getAccessToken(String code) throws UnirestException, JSONException { String access_token_body = "client_id=" + Constant_Auth.CLIENT_ID + "&client_secret=" + Constant_Auth.CLIENT_SECRET + "&code=" + code; HttpResponse<JsonNode> response1 = Unirest.post("https://slack.com/api/oauth.access") .header("cache-control", "no-cache") .header("postman-token", "c207fe41-f818-2d0c-e9c9-2df4f72967de") .header("content-type", "application/x-www-form-urlencoded") .body(access_token_body) .asJson(); JSONObject accessdata = response1.getBody().getObject(); System.out.println("Slack accessdata after authentication = " + accessdata); return accessdata; }
@SuppressWarnings("unchecked") public String delete(String url, Map<String, String> headers) throws URISyntaxException { HttpResponse<String> httpResponse = null; if (!validatorUtil.isHttpURLValid(url)) { throw new URISyntaxException(url, "The URL is not absolute"); } try { httpResponse = Unirest.delete(url).headers(headers).asString(); } catch (UnirestException e) { LOGGER.error("Exception occured while making post call"); JSONObject errorObject = new JSONObject(); errorObject.put("status", "500"); errorObject.put("message", e.getLocalizedMessage()); return errorObject.toJSONString(); } return httpResponse.getStatusText(); }