@Test public void test_formParams_work() throws Exception { Javalin app = Javalin.create().port(0).start(); app.before("/body-reader", ctx -> ctx.header("X-BEFORE", ctx.formParam("username"))); app.post("/body-reader", ctx -> ctx.result(ctx.formParam("password"))); app.after("/body-reader", ctx -> ctx.header("X-AFTER", ctx.formParam("repeat-password"))); HttpResponse<String> response = Unirest .post("http://localhost:" + app.port() + "/body-reader") .body("username=some-user-name&password=password&repeat-password=password") .asString(); assertThat(response.getHeaders().getFirst("X-BEFORE"), is("some-user-name")); assertThat(response.getBody(), is("password")); assertThat(response.getHeaders().getFirst("X-AFTER"), is("password")); app.stop(); }
/** * Using the HttpMethod to return a http request. * @param params Parameters to be replaced. * @return The http request */ private HttpRequest requestHttp(Object... params) { String processedPath = processPath(params); HttpRequest request = null; switch (path.getMethod()) { case GET: request = Unirest.get(processedPath); break; case HEAD: request = Unirest.head(processedPath); break; case POST: request = Unirest.post(processedPath); break; case PUT: request = Unirest.put(processedPath); break; case PATCH: request = Unirest.patch(processedPath); break; case DELETE: request = Unirest.delete(processedPath); break; case OPTIONS: request = Unirest.options(processedPath); break; } processRequest(request); this.request = request; return request; }
public void execute(JobExecutionContext context) throws JobExecutionException { // Extract data from job Map<String, String> properties = (Map<String, String>) context.getMergedJobDataMap().get(Map.class.getCanonicalName()); Set<String> taskIds = (Set<String>) context.getMergedJobDataMap().get(Task.class.getCanonicalName()); taskIds.forEach(taskId -> { final String url = urlConverter( DEFAULT_PROTOCOL, properties.get(SERVER_IP), properties.get(SERVER_PORT), properties.get(SERVER_CONTEXT_PATH) + RETRY_PATH + "/" + taskId ); try { final HttpResponse<String> httpResponse = Unirest.get(url).asString(); } catch (UnirestException e) { LOGGER.error("UnirestException", e); } }); }
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; }
public static String paste(String toSend) { try { String pasteToken = Unirest.post("https://hastebin.com/documents") .header("User-Agent", "Mantaro") .header("Content-Type", "text/plain") .body(toSend) .asJson() .getBody() .getObject() .getString("key"); return "https://hastebin.com/" + pasteToken; } catch (UnirestException e) { log.warn("Hastebin is being funny, huh? Cannot send or retrieve paste.", e); return "Bot threw ``" + e.getClass().getSimpleName() + "``" + " while trying to upload paste, check logs"; } }
private synchronized void triggerJob() { try { logger.log(Level.INFO,"Starting Jenkins job: " + JOB_NAME); String result = null; switch(getJobType()) { case Parametrized: result = Unirest.post(JENKINS_URL + "/job/" + JOB_NAME + "/build").basicAuth(USER, API_TOKEN) .field("json", getJSON()) .asBinary().getStatusText(); break; case Normal: result = Unirest.post(JENKINS_URL + "/job/" + JOB_NAME + "/build").basicAuth(USER, API_TOKEN) .asBinary().getStatusText(); break; } logger.log(Level.INFO,"Done. Job '" + JOB_NAME + "' status: " + result); } catch (UnirestException e) { e.printStackTrace(); } }
/** * Logs out with the session identifier. * * @param url REST API Url. * @param sessionId Session identifier. */ public static void logout(String url, String sessionId) { try { Map<String, String> session = new LinkedHashMap<String, String>(); session.put("user_name", sessionId); ObjectMapper mapper = new ObjectMapper(); String jsonSessionData = mapper.writeValueAsString(session); Map<String, Object> request = new LinkedHashMap<String, Object>(); request.put("method", "logout"); request.put("input_type", "json"); request.put("response_type", "json"); request.put("rest_data", jsonSessionData); Unirest.post(url) .fields(request) .asString(); } catch (Exception exception) { } }
@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 getIdentifier(String token) throws UnirestException, InvalidAccountException { String[] codes = token.split("\\|"); HttpResponse<JsonNode> me = Unirest.get("https://api.tumblr.com/v2/user/info?" + getOauthRequest("https://api.tumblr.com/v2/user/info", "oauth_token="+codes[0], "oob", "GET", codes[1])) .header("User-Agent", "pxls.space") .asJson(); JSONObject json = me.getBody().getObject(); if (json.has("error")) { return null; } else { try { return json.getJSONObject("response").getJSONObject("user").getString("name"); } catch (JSONException e) { return null; } } }
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 getToken(String code) throws UnirestException { HttpResponse<JsonNode> response = Unirest.post("https://www.reddit.com/api/v1/access_token") .header("User-Agent", "pxls.space") .field("grant_type", "authorization_code") .field("code", code) .field("redirect_uri", getCallbackUrl()) .basicAuth(App.getConfig().getString("oauth.reddit.key"), App.getConfig().getString("oauth.reddit.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://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 JSONArray getAllDeployments() { JSONArray deployments = new JSONArray(); try { deployments = Unirest.get(MessageFormat.format("http://{0}:{1}/deployments", host, port)) .header("accept", "application/json") .header("Content-Type", "application/json") .asJson() .getBody().getArray(); } catch (UnirestException e) { e.printStackTrace(); } return deployments; }
public JSONObject getDeploymentById(int id) { JSONObject deployment = new JSONObject(); try { deployment = Unirest.get(MessageFormat.format("http://{0}:{1}/deployment/{2}", host, port, id)) .header("accept", "application/json") .header("Content-Type", "application/json") .asJson() .getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return deployment; }
public JSONObject addDeployment(String name) { JSONObject addedDeployment = new JSONObject(); try { addedDeployment = Unirest.post(MessageFormat.format("http://{0}:{1}/deployment", host, port)) .header("accept", "application/json") .header("Content-Type", "application/json") .body(new JSONObject() //Using this because the field functions couldn't get translated to an acceptable json .put("name", name) .toString()) .asJson() .getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return addedDeployment; }
public JSONArray getModelsForDeployment(int id) { JSONArray allModelsOfDeployment = new JSONArray(); try { allModelsOfDeployment = Unirest.get(MessageFormat.format("http://{0}:{1}/deployment/{2}/models", host, port, id)) .header("accept", "application/json") .header("Content-Type", "application/json") .asJson() .getBody().getArray(); } catch (UnirestException e) { e.printStackTrace(); } return allModelsOfDeployment; }
public String getAuthToken(String userId, String password) { String authToken = null; try { authToken = Unirest.post(MessageFormat.format("http://{0}:{1}/login", host, port)) .header("accept", "application/json") .header("Content-Type", "application/json") .body(new JSONObject() //Using this because the field functions couldn't get translated to an acceptable json .put("userId", userId) .put("password", password) .toString()) .asJson() .getBody().getObject().getString("token"); } catch (UnirestException e) { e.printStackTrace(); } return authToken; }
public JSONObject addKNN(String name, String fileLocation, int scale, String uri) { JSONObject knn = new JSONObject(); try { List<String> uriList = new ArrayList<String>(); uriList.add(uri); knn = Unirest.post(MessageFormat.format("http://{0}:{1}/deployment/{2}/model", host, port, deploymentID)) .header("accept", "application/json") .header("Content-Type", "application/json") .body(new JSONObject() .put("name", name) .put("modelType", "knn") .put("fileLocation", fileLocation) .put("scale", scale) .put("uri", uriList) .toString()) .asJson() .getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return knn; }
@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(); }
static void notifyEvent(String lastFetchedRound, String shortName) { System.out.printf("Notify round \"%s\", event \"%s\"%n", lastFetchedRound, shortName); if (!isRecordingRequired()) { return; } try { HttpResponse<String> stringHttpResponse = Unirest.post(RECORDING_SYSTEM_ENDPOINT + "/notify") .body(lastFetchedRound+"/"+shortName) .asString(); if (stringHttpResponse.getStatus() != 200) { System.err.println("Recording system returned code: "+stringHttpResponse.getStatus()); return; } if (!stringHttpResponse.getBody().startsWith("ACK")) { System.err.println("Recording system returned body: "+stringHttpResponse.getStatus()); } } catch (UnirestException e) { System.err.println("Could not reach recording system: " + e.getMessage()); } }
public JSONObject addModel(String name, String fileLocation, int scale, String uri) { JSONObject model = new JSONObject(); try { List<String> uriList = new ArrayList<String>(); uriList.add(uri); model = Unirest.post(MessageFormat.format("http://{0}:{1}/deployment/{2}/model", host, port, deploymentID)) .header("accept", "application/json") .header("Content-Type", "application/json") .body(new JSONObject() .put("name", name) .put("modelType", "model") .put("fileLocation", fileLocation) .put("scale", scale) .put("uri", uriList) .toString()) .asJson() .getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return model; }
public JSONObject reimportModel(int modelID, String name, String fileLocation) { JSONObject model = new JSONObject(); try { model = Unirest.post(MessageFormat.format("http://{0}:{1}/deployment/{2}/model/{3}", host, port, deploymentID, modelID)) .header("accept", "application/json") .header("Content-Type", "application/json") .body(new JSONObject() .put("name", name) .put("modelType", "model") .put("fileLocation", fileLocation) .toString()) .asJson() .getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return model; }
public JSONObject deleteModel(int modelID) { JSONObject model = new JSONObject(); try { model = Unirest.delete(MessageFormat.format("http://{0}:{1}/deployment/{2}/model/{3}", host, port, deploymentID, modelID)) .header("accept", "application/json") .header("Content-Type", "application/json") .asJson() .getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return model; }
public JSONObject setModelState(int modelID, String state) { JSONObject model = new JSONObject(); try { model = Unirest.delete(MessageFormat.format("http://{0}:{1}/deployment/{2}/model/{3}/state", host, port, deploymentID, modelID)) .header("accept", "application/json") .header("Content-Type", "application/json") .body(new JSONObject() .put("name", state) .toString()) .asJson() .getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return model; }
public JSONObject addTransform(String name, String fileLocation, int scale, String uri) { JSONObject transform = new JSONObject(); try { List<String> uriList = new ArrayList<String>(); uriList.add(uri); transform = Unirest.post(MessageFormat.format("http://{0}:{1}/deployment/{2}/model", host, port, deploymentID)) .header("accept", "application/json") .header("Content-Type", "application/json") .body(new JSONObject() .put("name", name) .put("modelType", "transform") .put("fileLocation", fileLocation) .put("scale", scale) .put("uri", uriList) .toString()) .asJson() .getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return transform; }
public JSONObject setTransformState(int transformID, String state) { JSONObject transform = new JSONObject(); try { transform = Unirest.delete(MessageFormat.format("http://{0}:{1}/deployment/{2}/model/{3}/state", host, port, deploymentID, transformID)) .header("accept", "application/json") .header("Content-Type", "application/json") .body(new JSONObject() .put("name", state) .toString()) .asJson() .getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return transform; }
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(); }
public Optional<String> getToken() { final ListenableFuture<String> masterPassword = encyptionKeyProvider.getMasterPassword(); if (!masterPassword.isDone()) { return Optional.empty(); } final String key = encyptionKeyProvider.getImmediatePassword(); final String s = key + " meta"; final ECKey privKey = ECKey.fromPrivate(Sha256Hash.twiceOf(s.getBytes(Charsets.UTF_8)).getBytes()); /* @POST @Path("/token") @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response createToken(@QueryParam("timestamp") Long nonce, @QueryParam("signature") String signature) { */ // } final long timeStamp = Instant.now().toEpochMilli(); try { final String url = rootPath + "auth/token"; final HttpResponse<String> token = Unirest.post(url) .queryString("timestamp", timeStamp) .queryString("signature", privKey.signMessage(String.valueOf(timeStamp))) .asString(); if (token.getStatus() != 200) { return Optional.empty(); } return Optional.of(token.getBody()); } catch (UnirestException e) { LOGGER.error("exception from remote service when trying to get token", e); return Optional.empty(); } }
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(); } }
@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(); } }
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); } }
protected HttpResponse<JsonNode> getNextIssuesAPI(Integer page, Instant since) throws UnirestException { GetRequest unirest = Unirest.get(constructUrl(page, since)); if (!config.getAuthUsername().isEmpty() && !config.getAuthPassword().isEmpty() ){ unirest = unirest.basicAuth(config.getAuthUsername(), config.getAuthPassword()); } log.debug(String.format("GET %s", unirest.getUrl())); return unirest.asJson(); }
/** * 该方法用于后台取Token */ public Map<String, Object> getToken(HttpServletRequest request) { Map<String, Object> result = new HashMap<String, Object>(); result.put("isSuccess", false); String username = request.getParameter("username"); String password = request.getParameter("password"); String accessId = request.getParameter("accessId"); String accessSecret = request.getParameter("accessSecret"); if (username == null || password == null) { username = accessId; password = accessSecret; } if (username == null || password == null) { result.put("reason", "Parameter Error"); return result; } HttpResponse<String> response; try { String url = "http://localhost:8080/loginServer/oauth/token?grant_type=password&username=%s&password=%s"; response = Unirest.post(String.format(url, username, password)) .header("authorization", "Basic Z29vZHNhdmU6Z29vZHNhdmU=") .header("cache-control", "no-cache") .asString(); if (response.getStatus() >= 200 && response.getStatus() < 400) { result.put("isSuccess", true); result.put("access_token", JSON.parseObject(response.getBody()).get("access_token")); result.put("token_type", JSON.parseObject(response.getBody()).get("token_type")); result.put("refresh_token", JSON.parseObject(response.getBody()).get("refresh_token")); result.put("expires_in", JSON.parseObject(response.getBody()).get("expires_in")); result.put("scope", JSON.parseObject(response.getBody()).get("scope")); } else { result.put("reason", "username or password failed"); } } catch (UnirestException e) { e.printStackTrace(); result.put("isSuccess", false); result.put("reason", "inner error"); } return result; }
/** * 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()); }