com.mashape.unirest.http.Unirest Java Examples
The following examples show how to use
com.mashape.unirest.http.Unirest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RocketChatClientCallBuilder.java From rocket-chat-rest-client with MIT License | 7 votes |
private void login() throws IOException { HttpResponse<JsonNode> loginResult; try { loginResult = Unirest.post(serverUrl + "v1/login").field("username", user).field("password", password).asJson(); } catch (UnirestException e) { throw new IOException(e); } if (loginResult.getStatus() == 401) throw new IOException("The username and password provided are incorrect."); if (loginResult.getStatus() != 200) throw new IOException("The login failed with a result of: " + loginResult.getStatus() + " (" + loginResult.getStatusText() + ")"); JSONObject data = loginResult.getBody().getObject().getJSONObject("data"); this.authToken = data.getString("authToken"); this.userId = data.getString("userId"); }
Example #2
Source File: Authorization.java From SKIL_Examples with Apache License 2.0 | 6 votes |
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() .put("userId", userId) .put("password", password) .toString()) .asJson() .getBody().getObject().getString("token"); } catch (UnirestException e) { e.printStackTrace(); } return authToken; }
Example #3
Source File: BasicFunctionalityTest.java From elepy with Apache License 2.0 | 6 votes |
@Test void cant_Login_and_CreateSuperUser_afterOneHasBeenCreated() throws JsonProcessingException, UnirestException { createInitialUsersViaHttp(); User userToUpdate = new User("user", "user", "", Collections.singletonList(Permissions.SUPER_USER)); final HttpResponse<String> authorizedFind = Unirest .post(elepy + "/users") .basicAuth("[email protected]", "[email protected]") .body(json(userToUpdate)) .asString(); final User user = userCrud.getById("user").orElseThrow(); assertThat(authorizedFind.getStatus()).isEqualTo(403); assertThat(user.getRoles().size()).isEqualTo(0); }
Example #4
Source File: StateMachineResourceTest.java From flux with Apache License 2.0 | 6 votes |
@Test public void testPostScheduledEvent_withoutCorrelationIdTag() throws Exception { String stateMachineDefinitionJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("state_machine_definition.json")); Unirest.post(STATE_MACHINE_RESOURCE_URL).header("Content-Type", "application/json").body(stateMachineDefinitionJson).asString(); String eventJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("event_data.json")); //request with searchField param missing final HttpResponse<String> eventPostResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL + SLASH + "magic_number_1" + "/context/events?triggerTime=123").header("Content-Type", "application/json").body(eventJson).asString(); assertThat(eventPostResponse.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); //request with searchField param having value other than correlationId final HttpResponse<String> eventPostResponseWithWrongTag = Unirest.post(STATE_MACHINE_RESOURCE_URL + SLASH + "magic_number_1" + "/context/events?searchField=dummy&triggerTime=123").header("Content-Type", "application/json").body(eventJson).asString(); assertThat(eventPostResponseWithWrongTag.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); }
Example #5
Source File: Chat.java From JavaTelegramBot-API with GNU General Public License v3.0 | 6 votes |
/** * Gets the ChatMember object for a specific user based on their ID in respect to this chat * * @param userID The ID of the user that you want the ChatMember object for * * @return The ChatMember object for this user or Null if the request failed */ default ChatMember getChatMember(long userID) { try { MultipartBody request = Unirest.post(getBotInstance().getBotAPIUrl() + "getChatMember") .field("chat_id", getId(), "application/json; charset=utf8;") .field("user_id", userID); HttpResponse<String> response = request.asString(); JSONObject jsonResponse = processResponse(response); if (jsonResponse != null && Utils.checkResponseStatus(jsonResponse)) { return createChatMember(jsonResponse.getJSONObject("result")); } } catch (UnirestException e) { e.printStackTrace(); } return null; }
Example #6
Source File: BasicFunctionalityTest.java From elepy with Apache License 2.0 | 6 votes |
@Test void can_GetToken_and_Login() throws UnirestException { elepy.createInitialUserViaHttp("ryan", "susana"); elepy.get("/random-secured-route", context -> { context.requirePermissions(Permissions.AUTHENTICATED); context.result(Message.of("Perfect!", 200)); }); final var getTokenResponse = Unirest.post(elepy + "/elepy/token-login") .basicAuth("ryan", "susana") .asString(); final var token = getTokenResponse.getBody().replaceAll("\"", ""); final var authenticationResponse = Unirest.get(elepy + "/random-secured-route").header("Authorization", "Bearer " + token).asString(); assertThat(authenticationResponse.getStatus()).isEqualTo(200); }
Example #7
Source File: MockInstanceConnector.java From cloudbreak with Apache License 2.0 | 6 votes |
@Override public List<CloudVmInstanceStatus> start(AuthenticatedContext authenticatedContext, List<CloudResource> resources, List<CloudInstance> vms) { List<CloudVmInstanceStatus> cloudVmInstanceStatuses = new ArrayList<>(); for (CloudInstance instance : vms) { CloudVmInstanceStatus instanceStatus = getVmInstanceStatus(authenticatedContext, instance, "start"); cloudVmInstanceStatuses.add(instanceStatus); } MockCredentialView mockCredentialView = mockCredentialViewFactory.createCredetialView(authenticatedContext.getCloudCredential()); LOGGER.info("start instance statuses to mock spi, server address: " + mockCredentialView.getMockEndpoint()); try { Unirest.post(mockCredentialView.getMockEndpoint() + "/spi/start_instances").asString(); } catch (UnirestException e) { LOGGER.error("Error when instances got started", e); } return cloudVmInstanceStatuses; }
Example #8
Source File: HttpClientTest.java From apicurio-studio with Apache License 2.0 | 6 votes |
@Test public void testEncodedPath_Unirest() throws Exception { String url = new Endpoint("http://127.0.0.1:" + HTTP_PORT + "/echo/encoded%2Fpath").toString(); HttpRequest request = Unirest.get(url); HttpResponse<com.mashape.unirest.http.JsonNode> response = request.asJson(); Assert.assertEquals(200, response.getStatus()); JSONObject responseObj = response.getBody().getObject(); String method = responseObj.getString("method"); String uri = responseObj.getString("uri"); Assert.assertEquals("GET", method); // Note: Unirest messes with the encoded path, incorrectly changing it from "/echo/encoded%2Fpath" // to "/echo/encoded/path" prior to making the HTTP request. This is why Unirest is not used in // the GitLab source connector. Assert.assertEquals("/echo/encoded/path", uri); }
Example #9
Source File: MicrocksConnector.java From apicurio-studio with Apache License 2.0 | 6 votes |
/** * Figures out the URL of the Keycloak server that is protecting Microcks. */ private String getKeycloakURL() throws MicrocksConnectorException { if (this._keycloakURL == null) { // Retrieve the Keycloak configuration to build keycloakURL. HttpResponse<JsonNode> keycloakConfig = null; try { keycloakConfig = Unirest.get(this.apiURL + "/keycloak/config") .header("Accept", "application/json").asJson(); } catch (UnirestException e) { logger.error("Exception while connecting to Microcks backend", e); throw new MicrocksConnectorException( "Exception while connecting Microcks backend. Check URL."); } if (keycloakConfig.getStatus() != 200) { logger.error("Keycloak config cannot be fetched from Microcks server, check configuration"); throw new MicrocksConnectorException( "Keycloak configuration cannot be fetched from Microcks. Check URL."); } String authServer = keycloakConfig.getBody().getObject().getString("auth-server-url"); String realmName = keycloakConfig.getBody().getObject().getString("realm"); this._keycloakURL = authServer + "/realms/" + realmName; } return this._keycloakURL; }
Example #10
Source File: HttpClientLiveTest.java From tutorials with MIT License | 6 votes |
@Test public void shouldReturnStatusAccepted() throws UnirestException { Map<String, String> headers = new HashMap<String, String>(); headers.put("accept", "application/json"); headers.put("Authorization", "Bearer 5a9ce37b3100004f00ab5154"); Map<String, Object> fields = new HashMap<String, Object>(); fields.put("name", "Sam Baeldung"); fields.put("id", "PSP123"); HttpResponse<JsonNode> jsonResponse = Unirest.put("http://www.mocky.io/v2/5a9ce7853100002a00ab515e") .headers(headers) .fields(fields) .asJson(); assertNotNull(jsonResponse.getBody()); assertEquals(202, jsonResponse.getStatus()); }
Example #11
Source File: Owl2Neo4J.java From owl2neo4j with MIT License | 6 votes |
private void queryNeo4J (JsonObject json, String url, String errorTitle) { try { HttpResponse<JsonNode> response = Unirest.post(url) .body(json.toString()) .asJson(); if (this.verbose_output) { System.out.println("CQL: " + json); this.cqlLogger.info(json.toString()); } checkForError(response); } catch (Exception e) { print_error(ANSI_RESET_DIM + errorTitle); print_error("CQL: " + json); print_error(e.getMessage()); System.exit(1); } }
Example #12
Source File: HealthChecker.java From dropwizard-experiment with MIT License | 6 votes |
public boolean check() throws InterruptedException { try { HttpResponse<String> health = Unirest.get(url + "/admin/healthcheck") .basicAuth("test", "test") .asString(); if (health.getStatus() == 200) { log.info("Healthy with {}", health.getBody()); return true; } else { log.error("Unhealthy with {}", health.getBody()); return false; } } catch (UnirestException e) { if (e.getCause() instanceof HttpHostConnectException && duration < maxDuration) { log.info("Unable to connect, retrying..."); duration = duration + DELAY; Thread.sleep(TimeUnit.SECONDS.toMillis(DELAY)); return check(); } log.error("Unable to connect.", e); return false; } }
Example #13
Source File: BladeTest.java From blade with Apache License 2.0 | 6 votes |
@Test public void testListen() throws Exception { Blade blade = Blade.of(); blade.listen(9001).start().await(); try { int code = Unirest.get("http://127.0.0.1:9001").asString().getStatus(); assertEquals(404, code); } finally { blade.stop(); try { new Socket("127.0.0.1", 9001); Assert.fail("Server is still running"); } catch (ConnectException e) { } } }
Example #14
Source File: BasicFunctionalityTest.java From elepy with Apache License 2.0 | 6 votes |
@Test public void can_CreateItem() throws UnirestException, JsonProcessingException { final long count = resourceCrud.count(); final Resource resource = validObject(); resource.setUniqueField("uniqueCreate"); final String s = elepy.objectMapper().writeValueAsString(resource); final HttpResponse<String> postRequest = Unirest.post(elepy + "/resources").body(s).asString(); assertThat(postRequest.getStatus()).as(postRequest.getBody()).isEqualTo(201); assertThat(resourceCrud.count()).isEqualTo(count + 1); }
Example #15
Source File: HttpTestBean.java From BotServiceStressToolkit with MIT License | 6 votes |
@Override public SampleResult sample(Entry entry) { SampleResult res = new SampleResult(); res.setSampleLabel(getName()); res.sampleStart(); res.setDataType(SampleResult.TEXT); try { JMeterContext context = getThreadContext(); JMeterVariables vars = context.getVariables(); String body = Unirest.get("http://www.uol.com.br").asString().getBody(); res.setResponseData(body, null); res.sampleEnd(); res.setSuccessful(true); } catch (UnirestException e) { res.setResponseData(e.toString(), null); res.sampleEnd(); res.setSuccessful(false); } return res; }
Example #16
Source File: BasicFunctionalityTest.java From elepy with Apache License 2.0 | 6 votes |
@BeforeAll protected void setUpAll() { HttpClient httpClient = HttpClients.custom() .disableCookieManagement() .build(); Unirest.setHttpClient(httpClient); elepy = ElepySystemUnderTest.create(); elepy.addModel(Resource.class); elepy.addModel(CustomUser.class); this.configureElepy(elepy); elepy.start(); resourceCrud = elepy.getCrudFor(Resource.class); userCrud = elepy.getCrudFor(User.class); }
Example #17
Source File: AuthHelper.java From BotServiceStressToolkit with MIT License | 6 votes |
public static TokenResponse getToken(String appId, String clientSecret) throws AuthenticationException { HttpResponse<InputStream> postResponse; try { postResponse = Unirest.post("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token") .field("grant_type", "client_credentials") .field("client_id", appId) .field("client_secret", clientSecret) .field("scope", String.format("%s/.default", appId)).asBinary(); if (postResponse.getStatus() == 200) { Jsonb jsonb = JsonbBuilder.create(); TokenResponse resp = jsonb.fromJson(postResponse.getBody(), TokenResponse.class); return resp; } else { throw new AuthenticationException("Status code is not 200: " + postResponse.getStatus() + ". Response text: " + postResponse.getStatusText()); } } catch (UnirestException e) { throw new AuthenticationException("Error authenticating Bot", e); } }
Example #18
Source File: StateMachineResourceTest.java From flux with Apache License 2.0 | 6 votes |
@Test public void testEventUpdate_taskCancelled() throws Exception { String stateMachineDefinitionJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream( "state_machine_definition.json")); final HttpResponse<String> smCreationResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL).header( "Content-Type", "application/json").body(stateMachineDefinitionJson).asString(); Event event = eventsDAO.findBySMIdAndName(smCreationResponse.getBody(), "event0"); assertThat(event.getStatus()).isEqualTo(Event.EventStatus.pending); /* Mark the task path as cancelled. */ TestWorkflow.shouldCancel = true; try { testEventUpdate_IneligibleTaskStatus_Util(smCreationResponse); } finally { TestWorkflow.shouldCancel = false; } }
Example #19
Source File: Network.java From minicraft-plus-revived with GNU General Public License v3.0 | 6 votes |
public static void findLatestVersion(Action callback) { new Thread(() -> { // fetch the latest version from github if (debug) System.out.println("Fetching release list from GitHub..."); try { HttpResponse<JsonNode> response = Unirest.get("https://api.github.com/repos/chrisj42/minicraft-plus-revived/releases").asJson(); if (response.getStatus() != 200) { System.err.println("Version request returned status code " + response.getStatus() + ": " + response.getStatusText()); System.err.println("Response body: " + response.getBody()); latestVersion = new VersionInfo(VERSION, "", ""); } else { latestVersion = new VersionInfo(response.getBody().getArray().getJSONObject(0)); } } catch (UnirestException e) { e.printStackTrace(); latestVersion = new VersionInfo(VERSION, "", ""); } callback.act(); // finished. }).start(); }
Example #20
Source File: ImageSparkTransformServerTest.java From deeplearning4j with Apache License 2.0 | 6 votes |
@Test public void testImageServerSingleMultipart() throws Exception { File f = testDir.newFolder(); File imgFile = new ClassPathResource("datavec-spark-inference/testimages/class0/0.jpg").getTempFileFromArchive(f); JsonNode jsonNode = Unirest.post("http://localhost:9060/transformimage") .header("accept", "application/json") .field("file1", imgFile) .asJson().getBody(); INDArray result = getNDArray(jsonNode); assertEquals(1, result.size(0)); // System.out.println(result); }
Example #21
Source File: CorrectPermissionsTest.java From elepy with Apache License 2.0 | 6 votes |
@ParameterizedTest @ValueSource(strings = {ADMIN, USER_CORRECT_ROLE}) void shouldBeAbleTo_Delete(String userId) throws UnirestException { passwords.create(arbitraryPassword("initial")); final var response = setupAuth(getUserFromBase(userId), Unirest.delete(elepy + "/passwords/initial")) .asString(); assertThat(response.getStatus()) .as(response.getBody()) .isGreaterThanOrEqualTo(200) .isLessThan(300); assertThat(passwords.count()) .isEqualTo(0); }
Example #22
Source File: AliyunUtil.java From ZTuoExchange_framework with MIT License | 6 votes |
public static JSONObject doPost(String url,String body,String accessId,String accessKey) throws MalformedURLException, UnirestException { String method = "POST"; String accept = "application/json"; String content_type = "application/json"; String path = new URL(url).getFile(); String date = DateUtil.toGMTString(new Date()); // 1.对body做MD5+BASE64加密 String bodyMd5 = MD5Base64(body); String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n" + path; // 2.计算 HMAC-SHA1 String signature = HMACSha1(stringToSign, accessKey); // 3.得到 authorization header String authHeader = "Dataplus " + accessId + ":" + signature; HttpResponse<JsonNode> resp = Unirest.post(url) .header("accept",accept) .header("content-type",content_type) .header("date",date) .header("Authorization",authHeader) .body(body) .asJson(); JSONObject json = resp.getBody().getObject(); return json; }
Example #23
Source File: CorrectPermissionsTest.java From elepy with Apache License 2.0 | 6 votes |
@ParameterizedTest @ValueSource(strings = {ADMIN, USER_CORRECT_ROLE}) void shouldBeAbleTo_Update(String userId) throws UnirestException { final var initial = arbitraryPassword("initial"); passwords.create(initial); initial.setPassword("newPassword"); final var response = setupAuth(getUserFromBase(userId), Unirest.put(elepy + "/passwords/initial")) .body(json(initial)) .asString(); assertThat(response.getStatus()) .as(response.getBody()) .isGreaterThanOrEqualTo(200) .isLessThan(300); assertThat(passwords.count()) .isEqualTo(1); assertThat(passwords.getById(initial.getSavedLocation())) .hasValueSatisfying(password -> assertThat(password.getPassword()).isEqualTo("newPassword")); }
Example #24
Source File: HttpClientLiveTest.java From tutorials with MIT License | 6 votes |
@Test @Ignore public void whenAysncRequestShouldReturnOk() throws InterruptedException, ExecutionException { Future<HttpResponse<JsonNode>> future = Unirest.post("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154?mocky-delay=10000ms") .header("accept", "application/json") .asJsonAsync(new Callback<JsonNode>() { public void failed(UnirestException e) { // Do something if the request failed } public void completed(HttpResponse<JsonNode> response) { // Do something if the request is successful } public void cancelled() { // Do something if the request is cancelled } }); assertEquals(200, future.get() .getStatus()); }
Example #25
Source File: MitmproxyJavaTest.java From mitmproxy-java with Apache License 2.0 | 6 votes |
@Test public void NullInterceptorReturnTest() throws InterruptedException, TimeoutException, IOException, UnirestException { List<InterceptedMessage> messages = new ArrayList<>(); MitmproxyJava proxy = new MitmproxyJava(MITMDUMP_PATH, (InterceptedMessage m) -> { messages.add(m); return null; }, 8087, null); proxy.start(); Unirest.setProxy(new HttpHost("localhost", 8087)); Unirest.get("http://appium.io").header("myTestHeader", "myTestValue").asString(); proxy.stop(); assertThat(messages).isNotEmpty(); final InterceptedMessage firstMessage = messages.get(0); assertThat(firstMessage.getRequest().getUrl()).startsWith("http://appium.io"); assertThat(firstMessage.getRequest().getHeaders()).containsOnlyOnce(new String[]{"myTestHeader", "myTestValue"}); assertThat(firstMessage.getResponse().getStatusCode()).isEqualTo(200); }
Example #26
Source File: CorrectPermissionsTest.java From elepy with Apache License 2.0 | 6 votes |
@ParameterizedTest @ValueSource(strings = { USER_NO_ROLE, USER_INCORRECT_ROLE, NO_USER }) void shouldNotBeAbleTo_FindOne(String userId) throws UnirestException { passwords.create(arbitraryPassword("initial")); final var response = setupAuth(getUserFromBase(userId), Unirest.get(elepy + "/passwords/initial")) .asString(); assertThat(response.getStatus()) .as(response.getBody()) .isEqualTo(401); }
Example #27
Source File: ESTasks.java From elasticsearch with Apache License 2.0 | 6 votes |
public void waitForGreen(Integer numNodes) { LOGGER.debug("Wating for green and " + numNodes + " nodes."); Awaitility.await().atMost(5, TimeUnit.MINUTES).pollInterval(1, TimeUnit.SECONDS).until(() -> { // This can take some time, somtimes. try { List<String> esAddresses = getEsHttpAddressList(); // This may throw a JSONException if we call before the JSON has been generated. Hence, catch exception. final JSONObject body = Unirest.get("http://" + esAddresses.get(0) + "/_cluster/health").asJson().getBody().getObject(); final boolean numberOfNodes = body.getInt("number_of_nodes") == numNodes; final boolean green = body.getString("status").equals("green"); final boolean initializingShards = body.getInt("initializing_shards") == 0; final boolean unassignedShards = body.getInt("unassigned_shards") == 0; LOGGER.debug(green + " and " + numberOfNodes + " and " + initializingShards + " and " + unassignedShards + ": " + body); return green && numberOfNodes && initializingShards && unassignedShards; } catch (Exception e) { LOGGER.debug(e); return false; } }); }
Example #28
Source File: CustomHttpClient.java From openvidu with Apache License 2.0 | 6 votes |
public CustomHttpClient(String url, String user, String pass) throws Exception { this.openviduUrl = url.replaceFirst("/*$", ""); this.headerAuth = "Basic " + Base64.getEncoder().encodeToString((user + ":" + pass).getBytes()); SSLContext sslContext = null; try { sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { throw new Exception("Error building custom HttpClient: " + e.getMessage()); } HttpClient unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Unirest.setHttpClient(unsafeHttpClient); }
Example #29
Source File: RedmineRestClient.java From scava with Eclipse Public License 2.0 | 5 votes |
protected InputStream search(Map<String, String> filter, int startAt, int pageSize) throws UnirestException { String url = apiUrl + "issues" + JSON_SUFFIX; GetRequest getRequest = Unirest.get(url); for (Entry<String, String> entry : filter.entrySet()) { getRequest = getRequest.field(entry.getKey(), entry.getValue()); } getRequest = getRequest.field("offset", startAt); getRequest = getRequest.field("limit", pageSize); HttpResponse<InputStream> response = executeRestCall(getRequest); return response.getRawBody(); }
Example #30
Source File: BaseTest.java From blueocean-plugin with MIT License | 5 votes |
public static String getJwtToken(Jenkins jenkins) throws UnirestException { HttpResponse<String> response = Unirest.get(jenkins.getRootUrl()+"jwt-auth/token/").header("Accept", "*/*") .header("Accept-Encoding","").asString(); String token = response.getHeaders().getFirst(X_BLUEOCEAN_JWT); Assert.assertNotNull(token); //we do not validate it for test optimization and for the fact that there are separate // tests that test token generation and validation return token; }