/** * @return The json object get by performing request. */ public JSONObject getAsJSONObject() { JSONObject json; try { HttpResponse<JsonNode> response = request.asJson(); checkRateLimit(response); handleErrorCode(response); JsonNode node = response.getBody(); if (node.isArray()) { throw new UnirestException("The request returns a JSON Array. Json: "+node.getArray().toString(4)); } else { json = node.getObject(); } } catch (UnirestException e) { throw new JSONException("Error Occurred while getting JSON Object: "+e.getLocalizedMessage()); } handleErrorResponse(json); return json; }
/** * @return The json array get by performing request. */ public JSONArray getAsJSONArray() { JSONArray json; try { HttpResponse<JsonNode> response = request.asJson(); checkRateLimit(response); handleErrorCode(response); JsonNode node = response.getBody(); if (!node.isArray()) { handleErrorResponse(node.getObject()); throw new UnirestException("The request returns a JSON Object. Json: "+node.getObject().toString(4)); } else { json = node.getArray(); } } catch (UnirestException e) { throw new JSONException("Error Occurred while getting JSON Array: "+e.getLocalizedMessage()); } return json; }
public static String processHttpRequest(String completeURL, Map<String, Object> params, Map<String, String> customHeaders, HttpMethod method) throws IOException { Map<String, String> headers = getDefaultHeader(); if (customHeaders != null) { headers.putAll(customHeaders); } HttpResponse<JsonNode> result = executeHttpMethod(completeURL, params, headers, method); if (result == null) { return null; } if (result.getStatus() != 200) { String exceptionResponse = result.getBody().toString(); throw new ServiceException((result.getStatus() + result.getStatusText()), exceptionResponse); } return result.getBody().toString(); }
public boolean download(String siaPath, Path destination) { LOGGER.info("downloading {}", siaPath); // final String dest = destination.toAbsolutePath().toString(); final FileTime lastModified = SiaFileUtil.getFileTime(siaPath); final String tempFileName = destination.getFileName().toString() + ".tempdownload"; Path tempFile = destination.getParent().resolve(tempFileName); final HttpResponse<String> downloadResult = siaCommand(SiaCommand.DOWNLOAD, ImmutableMap.of("destination", tempFile.toAbsolutePath().toString()), siaPath); final boolean noHosts = checkErrorFragment(downloadResult, NO_HOSTS); if (noHosts) { LOGGER.warn("unable to download file {} due to NO_HOSTS ", siaPath); return false; } if (statusGood(downloadResult)) { try { Files.setLastModifiedTime(tempFile, lastModified); Files.move(tempFile, destination, StandardCopyOption.ATOMIC_MOVE); Files.setLastModifiedTime(destination, lastModified); } catch (IOException e) { throw new RuntimeException("unable to do atomic swap of file " + destination); } return true; } LOGGER.warn("unable to download siaPath {} for an unexpected reason: {} ", siaPath, downloadResult.getBody()); return false; }
@Test public void test() throws UnirestException { gitHubSourceTask.config = new GitHubSourceConnectorConfig(initialConfig()); gitHubSourceTask.nextPageToVisit = 1; gitHubSourceTask.nextQuerySince = Instant.parse("2017-01-01T00:00:00Z"); gitHubSourceTask.gitHubHttpAPIClient = new GitHubAPIHttpClient(gitHubSourceTask.config); String url = gitHubSourceTask.gitHubHttpAPIClient.constructUrl(gitHubSourceTask.nextPageToVisit, gitHubSourceTask.nextQuerySince); System.out.println(url); HttpResponse<JsonNode> httpResponse = gitHubSourceTask.gitHubHttpAPIClient.getNextIssuesAPI(gitHubSourceTask.nextPageToVisit, gitHubSourceTask.nextQuerySince); if (httpResponse.getStatus() != 403) { assertEquals(200, httpResponse.getStatus()); Set<String> headers = httpResponse.getHeaders().keySet(); assertTrue(headers.contains("ETag")); assertTrue(headers.contains("X-RateLimit-Limit")); assertTrue(headers.contains("X-RateLimit-Remaining")); assertTrue(headers.contains("X-RateLimit-Reset")); assertEquals(batchSize.intValue(), httpResponse.getBody().getArray().length()); JSONObject jsonObject = (JSONObject) httpResponse.getBody().getArray().get(0); Issue issue = Issue.fromJson(jsonObject); assertNotNull(issue); assertNotNull(issue.getNumber()); assertEquals(2072, issue.getNumber().intValue()); } }
@Test public void testFileUpload() throws Exception { app.post("/testFileUpload", ctx -> { File uploadedFile = createTempFile("Not expected content ..."); FileUtils.copyInputStreamToFile(ctx.uploadedFile("upload").getContent(), uploadedFile); ctx.result(FileUtils.readFileToString(uploadedFile)); }); HttpResponse<String> response = Unirest.post(_UnirestBaseTest.origin + "/testFileUpload") .field("upload", createTempFile(EXPECTED_CONTENT)) .asString(); assertThat(response.getBody(), is(EXPECTED_CONTENT)); app.stop(); }
/** * Get List of records of response. * * @param response * @return */ private List<T> getList(HttpResponse<Records> response) { final Records records = response.getBody(); final List<T> list = new ArrayList<>(); for (Map<String, Object> record : records.getRecords()) { T item = null; try { item = transform(record, this.type.newInstance()); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { LOG.error(e.getMessage(), e); } list.add(item); } return list; }
@Test public void test_bodyReader() throws Exception { Javalin app = Javalin.create().port(0).start(); app.before("/body-reader", ctx -> ctx.header("X-BEFORE", ctx.body() + ctx.queryParam("qp"))); app.post("/body-reader", ctx -> ctx.result(ctx.body() + ctx.queryParam("qp"))); app.after("/body-reader", ctx -> ctx.header("X-AFTER", ctx.body() + ctx.queryParam("qp"))); HttpResponse<String> response = Unirest .post("http://localhost:" + app.port() + "/body-reader") .queryString("qp", "queryparam") .body("body") .asString(); assertThat(response.getHeaders().getFirst("X-BEFORE"), is("bodyqueryparam")); assertThat(response.getBody(), is("bodyqueryparam")); assertThat(response.getHeaders().getFirst("X-AFTER"), is("bodyqueryparam")); app.stop(); }
private Model getModelFromRemote(String graphQlQuery) { ObjectMapper mapper = new ObjectMapper(); ObjectNode bodyParam = mapper.createObjectNode(); // bodyParam.set("operationName", null); // bodyParam.set("variables", null); bodyParam.put("query", graphQlQuery); Model model = ModelFactory.createDefaultModel(); try { HttpResponse<InputStream> response = Unirest.post(url) .header("Accept", "application/rdf+xml") .body(bodyParam.toString()) .asBinary(); model.read(response.getBody(), "RDF/XML"); } catch (UnirestException e) { e.printStackTrace(); } return model; }
@Override public String getToken(String code) throws UnirestException { HttpResponse<JsonNode> response = Unirest.post("https://www.googleapis.com/oauth2/v4/token") .header("User-Agent", "pxls.space") .field("grant_type", "authorization_code") .field("code", code) .field("redirect_uri", getCallbackUrl()) .field("client_id", App.getConfig().getString("oauth.google.key")) .field("client_secret", App.getConfig().getString("oauth.google.secret")) .asJson(); JSONObject json = response.getBody().getObject(); if (json.has("error")) { return null; } else { return json.getString("access_token"); } }
public String getToken(String code) throws UnirestException { HttpResponse<JsonNode> response = Unirest.post("https://oauth.vk.com/access_token") .header("User-Agent", "pxls.space") .field("grant_type", "authorization_code") .field("code", code) .field("redirect_uri", getCallbackUrl()) .field("client_id", App.getConfig().getString("oauth.vk.key")) .field("client_secret", App.getConfig().getString("oauth.vk.secret")) .asJson(); JSONObject json = response.getBody().getObject(); if (json.has("error")) { return null; } else { return json.getString("access_token"); } }
public String getRedirectUrl(String state) { try { HttpResponse<String> response = Unirest.get("https://www.tumblr.com/oauth/request_token?" + getOauthRequestToken("https://www.tumblr.com/oauth/request_token")) .header("User-Agent", "pxls.space") .asString(); Map<String, String> query = parseQuery(response.getBody()); if (!query.get("oauth_callback_confirmed").equals("true")) { return "/"; } if (query.get("oauth_token") == null) { return "/"; } tokens.put(query.get("oauth_token"), query.get("oauth_token_secret")); return "https://www.tumblr.com/oauth/authorize?oauth_token=" + query.get("oauth_token"); } catch (UnirestException e) { return "/"; } }
public String getToken(String code) throws UnirestException { HttpResponse<JsonNode> response = Unirest.post("https://discordapp.com/api/oauth2/token") .header("User-Agent", "pxls.space") .field("grant_type", "authorization_code") .field("code", code) .field("redirect_uri", getCallbackUrl()) .basicAuth(App.getConfig().getString("oauth.discord.key"), App.getConfig().getString("oauth.discord.secret")) .asJson(); JSONObject json = response.getBody().getObject(); if (json.has("error")) { return null; } else { return json.getString("access_token"); } }
public String getIdentifier(String token) throws UnirestException, InvalidAccountException { HttpResponse<JsonNode> me = Unirest.get("https://discordapp.com/api/users/@me") .header("Authorization", "Bearer " + token) .header("User-Agent", "pxls.space") .asJson(); JSONObject json = me.getBody().getObject(); if (json.has("error")) { return null; } else { long id = json.getLong("id"); long signupTimeMillis = (id >> 22) + 1420070400000L; long ageMillis = System.currentTimeMillis() - signupTimeMillis; long minAgeMillis = App.getConfig().getDuration("oauth.discord.minAge", TimeUnit.MILLISECONDS); if (ageMillis < minAgeMillis){ long days = minAgeMillis / 86400 / 1000; throw new InvalidAccountException("Account too young"); } return json.getString("id"); } }
public String getIdentifier(String token) throws UnirestException, InvalidAccountException { HttpResponse<JsonNode> me = Unirest.get("https://oauth.reddit.com/api/v1/me") .header("Authorization", "bearer " + token) .header("User-Agent", "pxls.space") .asJson(); JSONObject json = me.getBody().getObject(); if (json.has("error")) { return null; } else { long accountAgeSeconds = (System.currentTimeMillis() / 1000 - json.getLong("created")); long minAgeSeconds = App.getConfig().getDuration("oauth.reddit.minAge", TimeUnit.SECONDS); if (accountAgeSeconds < minAgeSeconds){ long days = minAgeSeconds / 86400; throw new InvalidAccountException("Account too young"); } else if (!json.getBoolean("has_verified_email")) { throw new InvalidAccountException("Account must have a verified e-mail"); } return json.getString("name"); } }
public static List<String> retrieveAllFiles(String auth, String folder) throws IOException, UnirestException { List<String> lis= new LinkedList<String>(); HttpResponse<JsonNode> jsonResponse = Unirest.get("https://www.googleapis.com/drive/v2/files/root/children?q=title='"+folder+"'").header("Authorization","Bearer "+auth).asJson(); JSONObject jsonObject= new JSONObject(jsonResponse.getBody()); JSONArray array = jsonObject.getJSONArray("array"); for(int i=0;i<array.length();i++){ JSONArray jarray=array.getJSONObject(i).getJSONArray("items"); int j=jarray.length(); while(j>0){ String id=jarray.getJSONObject(0).getString("id"); auxRetrieveAllFiles(lis,auth,"https://www.googleapis.com/drive/v2/files?includeTeamDriveItems=false&pageSize=500&q='"+id+"'%20in%20parents"+"&key="+ MISConfig.getGoogle_api(),id); j--; } } return lis; }
@Test public void test_bodyReader_reverse() throws Exception { Javalin app = Javalin.create().port(0).start(); app.before("/body-reader", ctx -> ctx.header("X-BEFORE", ctx.queryParam("qp") + ctx.body())); app.post("/body-reader", ctx -> ctx.result(ctx.queryParam("qp") + ctx.body())); app.after("/body-reader", ctx -> ctx.header("X-AFTER", ctx.queryParam("qp") + ctx.body())); HttpResponse<String> response = Unirest .post("http://localhost:" + app.port() + "/body-reader") .queryString("qp", "queryparam") .body("body") .asString(); assertThat(response.getHeaders().getFirst("X-BEFORE"), is("queryparambody")); assertThat(response.getBody(), is("queryparambody")); assertThat(response.getHeaders().getFirst("X-AFTER"), is("queryparambody")); app.stop(); }
/** * Performs requests * @return HttpCode, the response status */ public HttpCode performRequest() { try { HttpResponse<JsonNode> response = request.asJson(); checkRateLimit(response); handleErrorCode(response); JsonNode node = response.getBody(); if (node != null && !node.isArray()) { handleErrorResponse(node.getObject()); } return HttpCode.getByKey(response.getStatus()); } catch (UnirestException e) { throw new RuntimeException("Fail to perform http request!"); } }
@SuppressWarnings("unchecked") private void handleErrorCode(HttpResponse response) { HttpCode error = HttpCode.getByKey(response.getStatus()); if (error.isServerError() || error.isFailure()) { if (error.equals(HttpCode.TOO_MANY_REQUESTS)) { // Rate limited checkRateLimit(response); } else { throw new HttpErrorException(error); } } else if (error == HttpCode.UNKNOWN){ throw new HttpErrorException(response.getStatus(), response.getStatusText()); } }
@Test public void test_justFilters_is404() throws Exception { Handler emptyHandler = ctx -> { }; app.before(emptyHandler); app.after(emptyHandler); HttpResponse<String> response = call(HttpMethod.GET, "/hello"); assertThat(response.getStatus(), is(404)); assertThat(response.getBody(), is("Not found")); }
@Test public void test_mappedException_isHandled() throws Exception { app.get("/mapped-exception", ctx -> { throw new Exception(); }).exception(Exception.class, (e, ctx) -> ctx.result("It's been handled.")); HttpResponse<String> response = GET_asString("/mapped-exception"); assertThat(response.getBody(), is("It's been handled.")); assertThat(response.getStatus(), is(200)); }
/** * Create the poll as represented by this object * @return ID of the created poll * @throws IOException Something bad happened when accessing the resource */ public int createPoll() throws UnirestException { HttpResponse<JsonNode> jsonResponse = Unirest.post(BASE_API) .header("Content-Type", "application/json") .body((new Gson()).toJson(this)) .asJson(); return jsonResponse.getBody().getObject().getInt("id"); }
private static boolean checkErrorFragment(HttpResponse<String> reply, String fragment) { if (reply == null) { throw new RuntimeException("reply was null!. checking for fragment: " + fragment); } if (statusGood(reply)) { return false; } final String body = reply.getBody(); if (body == null) { throw new RuntimeException("replybody was null! checking for fragment: " + fragment); } return body.contains(fragment); }
@Test public void test_haltBeforeWildcard_works() throws Exception { app.before("/admin/*", ctx -> { throw new HaltException(401); }); app.get("/admin/protected", ctx -> ctx.result("Protected resource")); HttpResponse<String> response = call(HttpMethod.GET, "/admin/protected"); assertThat(response.getStatus(), is(401)); assertThat(response.getBody(), not("Protected resource")); }
private HttpResponse<String> siaCommand(SiaCommand command, ImmutableMap<String, Object> params, String... extraCommand) { try { final HttpRequest httpRequest = command.unirest(path, extraCommand) .header("User-Agent", "Sia-Agent") .queryString(params); return httpRequest.asString(); } catch (UnirestException e) { throw new NoConnectException(e); } }
String sendAction(String action) throws ClientErrorException, ServerErrorException, OtherCommunicationException { try { String encodedPath = URLEncoder.encode(this.journeyId, "UTF-8"); String url = String.format("http://%s:%d/action/%s/%s", this.url, port, action, encodedPath); HttpResponse<String> response = Unirest.post(url) .header("Accept", this.acceptHeader) .header("Accept-Charset", "UTF-8") .asString(); ensureStatusOk(response); return response.getBody(); } catch (UnirestException | UnsupportedEncodingException e ) { throw new OtherCommunicationException("Could not perform POST request",e); } }
private static boolean statusGood(HttpResponse<String> response) { if (response == null) { return false; } final int status = response.getStatus(); return status >= 200 && status < 300; }
@Test public void test_enableCorsForSpecificOrigins() throws Exception { Javalin app1 = Javalin.create().port(0).enableCorsForOrigin("origin-1", "referer-1").start(); app1.get("/", ctx -> ctx.result("Hello")); HttpResponse<String> response = Unirest.get("http://localhost:" + app1.port() + "/").asString(); assertThat(response.getHeaders().get("Access-Control-Allow-Origin"), is(nullValue())); response = Unirest.get("http://localhost:" + app1.port() + "/").header("Origin", "origin-1").asString(); assertThat(response.getHeaders().get("Access-Control-Allow-Origin").get(0), is("origin-1")); response = Unirest.get("http://localhost:" + app1.port() + "/").header("Referer", "referer-1").asString(); assertThat(response.getHeaders().get("Access-Control-Allow-Origin").get(0), is("referer-1")); app1.stop(); }
/** * Un-initializes this client * * @return {@link Result} * @throws UnirestException */ public Result unInit() throws UnirestException { checkInitialized(); HttpResponse<ResponseResult> response = Unirest .delete(this.session.getUri()) .asObject(ResponseResult.class); this.session = null; this.heartbeatThread = null; return Result.forCode(response.getBody().getResult()); }
public void updateGraph(String type, JSONObject node) { JSONObject jsonObj = new JSONObject(); jsonObj.put(type, node); //System.out.println(jsonObj.toString()); try { HttpResponse<String> response = Unirest.post(url + "?operation=updateGraph") .header("content-type", "application/json") .header("cache-control", "no-cache") .body(jsonObj.toString()) .asString(); Integer i = 0; if (type.equals("ae")) { this.ECount++; i = this.ECount; } if (type.equals("an")) { this.VCount++; i = this.VCount; } System.out.println(i + " " + response.getStatus() + " " + response.getStatusText() + " " + response.getBody()); } catch(UnirestException e) { e.printStackTrace(); } }
public static void updateGraphTest() { //System.out.println(jsonObj.toString()); try { HttpResponse<JsonNode> response = Unirest.post(url + "?operation=updateGraph") .header("content-type", "application/json") .header("cache-control", "no-cache") .body("{\"an\":{\"520248\":{\"id\":520248,\"label\":\"artist\"}}}") .asJson(); System.out.println(response.getBody()); } catch(UnirestException e) { e.printStackTrace(); } }
@Test public void test_typedMappedException_isHandled() throws Exception { app.get("/typed-exception", ctx -> { throw new TypedException(); }).exception(TypedException.class, (e, ctx) -> { ctx.result(e.proofOfType()); }); HttpResponse<String> response = GET_asString("/typed-exception"); assertThat(response.getBody(), is("I'm so typed")); assertThat(response.getStatus(), is(200)); }
protected InputStream downloadLatestMetadataZip(String token) throws UnirestException { final HttpResponse<InputStream> response = Unirest.get(metadataUrl + "file/latestMeta") .header("X-Auth-Token", token) .asBinary(); if (response.getStatus() == 404) return null; return response.getBody(); }
@Test public void test_afterRuns_afterHalt() throws Exception { app.get("/some-route", ctx -> { throw new HaltException(401, "Stop!"); }).after(ctx -> { ctx.status(418); }); HttpResponse<String> response = call(HttpMethod.GET, "/some-route"); assertThat(response.getBody(), is("Stop!")); assertThat(response.getStatus(), is(418)); }
@Test public void test_moreSpecificException_isHandledFirst() throws Exception { app.get("/exception-priority", ctx -> { throw new TypedException(); }).exception(Exception.class, (e, ctx) -> { ctx.result("This shouldn't run"); }).exception(TypedException.class, (e, ctx) -> { ctx.result("Typed!"); }); HttpResponse<String> response = GET_asString("/exception-priority"); assertThat(response.getBody(), is("Typed!")); assertThat(response.getStatus(), is(200)); }
@Test public void testIsTestRepositoryAvailable() throws IOException, UnirestException { HttpResponse<RepositoryContainer> response = Unirest.get(seRepoTestServer.LOCALHOST_REPOS) .asObject(RepositoryContainer.class); RepositoryContainer repos = response.getBody(); assertTrue(repos.getRepositories().stream().map(Repository::getName).collect(Collectors.toList ()).contains(TestDataProvider.TEST_REPO)); }
@Override public UserProfile login(PlayerLogin playerLogin) { try { HttpResponse<UserProfile> userProfileResponse = Unirest.post(config.getBaseUrl() + "/mc/player/login") .header("x-access-token", config.getAuthToken()) .header("accept", "application/json") .header("Content-Type", "application/json") .body(playerLogin) .asObject(UserProfile.class); return userProfileResponse.getBody(); } catch (UnirestException e) { e.printStackTrace(); return null; } }
@Override public MapLoadResponse loadmap(Map map) { try { HttpResponse<MapLoadResponse> mapLoadResponse = Unirest.post(config.getBaseUrl() + "/mc/map/load") .header("x-access-token", config.getAuthToken()) .header("accept", "application/json") .header("Content-Type", "application/json") .body(map) .asObject(MapLoadResponse.class); return mapLoadResponse.getBody(); } catch (UnirestException e) { e.printStackTrace(); return null; } }
@Override public void addKill(Death death) { try { HttpResponse<JsonNode> jsonResponse = Unirest.post(config.getBaseUrl() + "/mc/death/new") .header("x-access-token", config.getAuthToken()) .header("accept", "application/json") .header("Content-Type", "application/json") .body(death) .asJson(); } catch (UnirestException e) { e.printStackTrace(); } }
@Override public void finishMatch(MatchFinishPacket matchFinishPacket) { try { HttpResponse<JsonNode> jsonResponse = Unirest.post(config.getBaseUrl() + "/mc/match/finish") .header("x-access-token", config.getAuthToken()) .header("accept", "application/json") .header("Content-Type", "application/json") .body(matchFinishPacket) .asJson(); } catch (UnirestException e) { e.printStackTrace(); } }