Java Code Examples for com.mashape.unirest.http.HttpResponse#getBody()
The following examples show how to use
com.mashape.unirest.http.HttpResponse#getBody() .
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: MediaWikiAPIPageExtractor.java From wandora with GNU General Public License v3.0 | 6 votes |
private String getArticleBody(String title) throws IOException{ StringBuilder queryBuilder = new StringBuilder(this.baseURL) .append("/index.php?action=raw&title=") .append(URLEncoder.encode(title)); HttpResponse<InputStream> resp; try { resp = Unirest.get(queryBuilder.toString()) .header("accept", "text/x-wiki") .asBinary(); } catch (UnirestException ex) { throw new IOException(ex); } InputStream body = resp.getBody(); String bodyString = IOUtils.toString(body,"UTF-8"); return bodyString; }
Example 2
Source File: Table.java From airtable.java with MIT License | 6 votes |
/** * 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; }
Example 3
Source File: ElasticsearchNodesResponse.java From elasticsearch with Apache License 2.0 | 6 votes |
private boolean endpointIsOk(JSONObject task) throws Exception { String url = "http://" + ElasticsearchParser.parseHttpAddress(task) + "/_nodes"; HttpResponse<String> response = Unirest.get(url).asString(); if (response.getStatus() < 200 || response.getStatus() >= 400) { LOGGER.debug("Polling Elasticsearch endpoint '" + url + "' returned bad status: " + response.getStatus() + " " + response.getStatusText()); return false; } JsonNode body = new JsonNode(response.getBody()); if (body.getObject().getJSONObject("nodes").length() != nodesCount) { LOGGER.debug("Polling Elasticsearch endpoint '" + url + "' returned wrong number of nodes (Expected " + nodesCount + " but got " + body.getObject().getJSONObject("nodes").length() + ")"); return false; } LOGGER.debug("Polling Elasticsearch endpoint '" + url + "' succeeded"); return true; }
Example 4
Source File: HelpFunc.java From df_data_service with Apache License 2.0 | 6 votes |
/** * Upload Flink client to flink rest server * @param postURL * @param jarFilePath * @return */ public static String uploadJar(String postURL, String jarFilePath) { HttpResponse<String> jsonResponse = null; try { jsonResponse = Unirest.post(postURL) .field("file", new File(jarFilePath)) .asString(); } catch (UnirestException e) { e.printStackTrace(); } JsonObject response = new JsonObject(jsonResponse.getBody()); if(response.containsKey("filename")) { return response.getString("filename"); } else { return ""; } }
Example 5
Source File: ProcessorTopicSchemaRegistry.java From df_data_service with Apache License 2.0 | 6 votes |
/** * Get schema compatibility from schema registry. * * @param schemaUri * @param schemaSubject * @return * @throws ConnectException */ public static String getCompatibilityOfSubject(String schemaUri, String schemaSubject) { String compatibility = null; String fullUrl = String.format("http://%s/config/%s", schemaUri, schemaSubject); HttpResponse<String> res = null; try { res = Unirest.get(fullUrl).header("accept", "application/vnd.schemaregistry.v1+json").asString(); LOG.debug("Subject:" + schemaSubject + " " + res.getBody()); if (res.getBody() != null) { if (res.getBody().indexOf("40401") > 0) { } else { JSONObject jason = new JSONObject(res.getBody().toString()); // This attribute is different from confluent doc. TODo check update later compatibility = jason.getString(ConstantApp.SCHEMA_REGISTRY_KEY_COMPATIBILITY_LEVEL); } } } catch (UnirestException e) { LOG.error(DFAPIMessage.logResponseMessage(9006, "exception - " + e.getCause())); } return compatibility; }
Example 6
Source File: EmaySMSProvider.java From ZTuoExchange_framework with MIT License | 5 votes |
@Override public MessageResult sendSingleMessage(String mobile, String content) throws UnirestException { log.info("sms content={}", content); HttpResponse<String> response = Unirest.post(gateway) .field("cdkey", username) .field("password", password) .field("phone", mobile) .field("message", content) .asString(); String resultXml = response.getBody(); log.info(" mobile : " + mobile + "content : " + content); log.info("result = {}", resultXml); return parseXml(resultXml); }
Example 7
Source File: Downloader.java From minimesos with Apache License 2.0 | 5 votes |
public String getFileContentAsString(String url) throws MinimesosException { HttpResponse<String> response = null; try { response = Unirest.get(url) .header("content-type", "*/*") .asString(); } catch (UnirestException e) { throw new MinimesosException(String.format("Cannot fetch file '%s': '%s'", url, e.getMessage())); } if (response.getStatus() != HttpStatus.SC_OK) { throw new MinimesosException(String.format("Cannot fetch file '%s': '%s'", url, response.getStatus())); } return response.getBody(); }
Example 8
Source File: StateMachineResourceTest.java From flux with Apache License 2.0 | 5 votes |
@Test public void testUnsideline() 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); // ask the task to fail with retriable error. TestWorkflow.shouldFail = true; try { String eventJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("event_data.json")); final HttpResponse<String> eventPostResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL + SLASH + smCreationResponse.getBody() + "/context/events").header("Content-Type", "application/json").body(eventJson).asString(); assertThat(eventPostResponse.getStatus()).isEqualTo(Response.Status.ACCEPTED.getStatusCode()); // give some time to execute Thread.sleep(6000); //status of state should be sidelined String smId = smCreationResponse.getBody(); State state4 = stateMachinesDAO.findById(smId).getStates().stream().filter(e -> e.getName().equals("test_state4")).findFirst().orElse(null); assertThat(state4).isNotNull(); assertThat(state4.getStatus()).isEqualTo(Status.sidelined); TestWorkflow.shouldFail = false; // unsideline final HttpResponse<String> unsidelineResponse = Unirest.put(STATE_MACHINE_RESOURCE_URL + "/" + smId + "/" + state4.getId() + "/unsideline").asString(); assertThat(unsidelineResponse.getStatus()).isEqualTo(Response.Status.ACCEPTED.getStatusCode()); Thread.sleep(2000); state4 = stateMachinesDAO.findById(smId).getStates().stream().filter(e -> e.getName().equals("test_state4")).findFirst().orElse(null); assertThat(state4).isNotNull(); assertThat(state4.getStatus()).isEqualTo(Status.completed); } finally { TestWorkflow.shouldFail = false; } }
Example 9
Source File: RequestExecutor.java From Bastion with GNU General Public License v3.0 | 5 votes |
private Response convertToRawResponse(HttpResponse<InputStream> httpResponse) { return new RawResponse(httpResponse.getStatus(), httpResponse.getStatusText(), httpResponse.getHeaders().entrySet().stream().flatMap(header -> header.getValue().stream().map(headerValue -> new ApiHeader(header.getKey(), headerValue))).collect(Collectors.toList()), httpResponse.getBody()); }
Example 10
Source File: CustomHttpClient.java From openvidu with Apache License 2.0 | 5 votes |
private JsonObject commonRest(HttpMethod method, String path, String body, int status) throws Exception { HttpResponse<?> jsonResponse = null; JsonObject json = null; path = openviduUrl + (path.startsWith("/") ? path : ("/" + path)); HttpRequest request = null; if (body != null && !body.isEmpty()) { switch (method) { case POST: request = Unirest.post(path); break; case PUT: request = Unirest.put(path); break; case PATCH: default: request = Unirest.patch(path); break; } ((HttpRequestWithBody) request).header("Content-Type", "application/json").body(body.replaceAll("'", "\"")); } else { switch (method) { case GET: request = Unirest.get(path); request.header("Content-Type", "application/x-www-form-urlencoded"); break; case POST: request = Unirest.post(path); break; case DELETE: request = Unirest.delete(path); request.header("Content-Type", "application/x-www-form-urlencoded"); break; case PUT: request = Unirest.put(path); default: break; } } request = request.header("Authorization", this.headerAuth); try { jsonResponse = request.asJson(); if (jsonResponse.getBody() != null) { jsonResponse.getBody(); json = JsonParser.parseString(((JsonNode) jsonResponse.getBody()).getObject().toString()) .getAsJsonObject(); } } catch (UnirestException e) { try { if (e.getCause().getCause().getCause() instanceof org.json.JSONException) { try { jsonResponse = request.asString(); } catch (UnirestException e1) { throw new Exception("Error sending request to " + path + ": " + e.getMessage()); } } else { throw new Exception("Error sending request to " + path + ": " + e.getMessage()); } } catch (NullPointerException e2) { throw new Exception("Error sending request to " + path + ": " + e.getMessage()); } } if (jsonResponse.getStatus() == 500) { log.error("Internal Server Error: {}", jsonResponse.getBody().toString()); } if (status != jsonResponse.getStatus()) { System.err.println(jsonResponse.getBody().toString()); throw new Exception(path + " expected to return status " + status + " but got " + jsonResponse.getStatus()); } return json; }
Example 11
Source File: PipelineBaseTest.java From blueocean-plugin with MIT License | 5 votes |
public <T> T build(Class<T> clzzz) { try { HttpRequest request = build(); HttpResponse<T> response = request.asObject(clzzz); Assert.assertEquals(response.getStatusText(), expectedStatus, response.getStatus()); return response.getBody(); } catch (UnirestException e) { throw new RuntimeException(e); } }
Example 12
Source File: Table.java From airtable.java with MIT License | 5 votes |
/** * Delete Record by given id * * @param id Id of the row to delete. * @return true if success. * @throws AirtableException */ public boolean destroy(String id) throws AirtableException { boolean isDeleted; HttpResponse<Delete> response; try { response = Unirest.delete(getTableEndpointUrl() + "/" + id) .header("accept", MIME_TYPE_JSON) .header("Authorization", getBearerToken()) .asObject(Delete.class); } catch (UnirestException e) { throw new AirtableException(e); } int code = response.getStatus(); if (200 == code) { Delete body = response.getBody(); isDeleted = body.isDeleted(); } else if (429 == code) { randomWait(); return destroy(id); } else { isDeleted = false; HttpResponseExceptionHandler.onResponse(response); } // if (!body.isDeleted()) { // throw new AirtableException("Record id: " + body.getId() + " could not be deleted."); // } return isDeleted; }
Example 13
Source File: EmaySMSProvider.java From ZTuoExchange_framework with MIT License | 5 votes |
@Override public MessageResult sendSingleMessage(String mobile, String content) throws UnirestException { log.info("sms content={}", content); HttpResponse<String> response = Unirest.post(gateway) .field("cdkey", username) .field("password", password) .field("phone", mobile) .field("message", content) .asString(); String resultXml = response.getBody(); log.info(" mobile : " + mobile + "content : " + content); log.info("result = {}", resultXml); return parseXml(resultXml); }
Example 14
Source File: DFDataProcessor.java From df_data_service with Apache License 2.0 | 4 votes |
/** * Start a Kafka connect in background to keep sinking meta data to mongodb * This is blocking process since it is a part of application initialization. */ private void startMetadataSink() { // Check if the sink is already started. If yes, do not start String restURI = "http://" + this.kafka_connect_rest_host + ":" + this.kafka_connect_rest_port + ConstantApp.KAFKA_CONNECT_REST_URL; String metaDBHost = config().getString("repo.connection.string", "mongodb://localhost:27017") .replace("//", "").split(":")[1]; String metaDBPort = config().getString("repo.connection.string", "mongodb://localhost:27017") .replace("//", "").split(":")[2]; String metaDBName = config().getString("db.name", "DEFAULT_DB"); // Create meta-database if it is not exist new MongoAdminClient(metaDBHost, Integer.parseInt(metaDBPort), metaDBName) .createCollection(this.COLLECTION_META) .close(); String metaSinkConnect = new JSONObject().put("name", "metadata_sink_connect").put("config", new JSONObject().put("connector.class", "org.apache.kafka.connect.mongodb.MongodbSinkConnector") .put("tasks.max", "2") .put("host", metaDBHost) .put("port", metaDBPort) .put("bulk.size", "1") .put("mongodb.database", metaDBName) .put("mongodb.collections", config().getString("db.metadata.collection.name", this.COLLECTION_META)) .put("topics", config().getString("kafka.topic.df.metadata", "df_meta"))).toString(); try { HttpResponse<String> res = Unirest.get(restURI + "/metadata_sink_connect/status") .header("accept", ConstantApp.HTTP_HEADER_APPLICATION_JSON_CHARSET) .asString(); if(res.getStatus() == ConstantApp.STATUS_CODE_NOT_FOUND) { // Add the meta sink Unirest.post(restURI) .header("accept", "application/json").header("Content-Type", "application/json") .body(metaSinkConnect).asString(); } // Add the avro schema for metadata as well since df_meta-value maybe added only String dfMetaSchemaSubject = config().getString("kafka.topic.df.metadata", "df_meta"); String schemaRegistryRestURL = "http://" + this.schema_registry_host_and_port + "/subjects/" + dfMetaSchemaSubject + "/versions"; HttpResponse<String> schmeaRes = Unirest.get(schemaRegistryRestURL + "/latest") .header("accept", ConstantApp.HTTP_HEADER_APPLICATION_JSON_CHARSET) .asString(); if(schmeaRes.getStatus() == ConstantApp.STATUS_CODE_NOT_FOUND) { // Add the meta sink schema Unirest.post(schemaRegistryRestURL) .header("accept", ConstantApp.HTTP_HEADER_APPLICATION_JSON_CHARSET) .header("Content-Type", ConstantApp.AVRO_REGISTRY_CONTENT_TYPE) .body(new JSONObject().put("schema", config().getString("df.metadata.schema", "{\"type\":\"record\"," + "\"name\": \"df_meta\"," + "\"fields\":[" + "{\"name\": \"cuid\", \"type\": \"string\"}," + "{\"name\": \"file_name\", \"type\": \"string\"}," + "{\"name\": \"file_size\", \"type\": \"string\"}, " + "{\"name\": \"file_owner\", \"type\": \"string\"}," + "{\"name\": \"last_modified_timestamp\", \"type\": \"string\"}," + "{\"name\": \"current_timestamp\", \"type\": \"string\"}," + "{\"name\": \"current_timemillis\", \"type\": \"long\"}," + "{\"name\": \"stream_offset\", \"type\": \"string\"}," + "{\"name\": \"topic_sent\", \"type\": \"string\"}," + "{\"name\": \"schema_subject\", \"type\": \"string\"}," + "{\"name\": \"schema_version\", \"type\": \"string\"}," + "{\"name\": \"status\", \"type\": \"string\"}]}" )).toString() ).asString(); LOG.info(DFAPIMessage.logResponseMessage(1008, "META_DATA_SCHEMA_REGISTRATION")); } else { LOG.info(DFAPIMessage.logResponseMessage(1009, "META_DATA_SCHEMA_REGISTRATION")); } JSONObject resObj = new JSONObject(res.getBody()); String status = "Unknown"; if (resObj.has("connector")) { status = resObj.getJSONObject("connector").get("state").toString(); } LOG.info(DFAPIMessage.logResponseMessage(1010, "topic:df_meta, status:" + status)); } catch (UnirestException ue) { LOG.error(DFAPIMessage .logResponseMessage(9015, "exception details - " + ue.getCause())); } }
Example 15
Source File: StateMachineResourceTest.java From flux with Apache License 2.0 | 4 votes |
@Test public void testEventUpdate() 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); /* Make the task fail, eventually sidelined. */ TestWorkflow.shouldFail = true; try { /* Since event0 is in pending state, updateEvent should fail. */ String eventJson0 = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream( "updated_event_data.json")); final HttpResponse<String> eventPostResponse0 = Unirest.post( STATE_MACHINE_RESOURCE_URL + SLASH + smCreationResponse.getBody() + "/context/eventupdate").header( "Content-Type", "application/json").body(eventJson0).asString(); assertThat(eventPostResponse0.getStatus()).isEqualTo(Response.Status.FORBIDDEN.getStatusCode()); String eventJson1 = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("event_data.json")); final HttpResponse<String> eventPostResponse1 = Unirest.post( STATE_MACHINE_RESOURCE_URL + SLASH + smCreationResponse.getBody() + "/context/events").header( "Content-Type", "application/json").body(eventJson1).asString(); assertThat(eventPostResponse1.getStatus()).isEqualTo(Response.Status.ACCEPTED.getStatusCode()); /* Give some time to task to execute, task thread sleeps for 1000 ms with 1 retry. */ Thread.sleep(4000); //status of state should be sidelined and should be able to update event data now String smId = smCreationResponse.getBody(); State state4 = stateMachinesDAO.findById(smId).getStates().stream().filter(e -> e.getName().equals("test_state4")) .findFirst().orElse(null); assertThat(state4).isNotNull(); assertThat(state4.getStatus()).isEqualTo(Status.sidelined); /* Make 'shouldFail' flag to false before update Event. Update Event will unsideline the dependent task * after event data update. */ TestWorkflow.shouldFail = false; String eventJson2 = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream( "updated_event_data.json")); final HttpResponse<String> eventPostResponse2 = Unirest.post( STATE_MACHINE_RESOURCE_URL + SLASH + smCreationResponse.getBody() + "/context/eventupdate").header( "Content-Type", "application/json").body(eventJson2).asString(); assertThat(eventPostResponse2.getStatus()).isEqualTo(Response.Status.ACCEPTED.getStatusCode()); /* Give some time to task to execute, task thread sleeps for 1000 ms */ Thread.sleep(2000); /* Assert for task completed and updated event data.*/ state4 = stateMachinesDAO.findById(smId).getStates().stream().filter(e -> e.getName().equals("test_state4")) .findFirst().orElse(null); assertThat(state4).isNotNull(); assertThat(state4.getStatus()).isEqualTo(Status.completed); Event event0 = eventsDAO.findBySMIdAndName(smId, "event0"); assertThat(event0.getEventData()).isEqualTo("50"); } finally { TestWorkflow.shouldFail = false; } }
Example 16
Source File: MediaWikiAPIPageExtractor.java From wandora with GNU General Public License v3.0 | 4 votes |
private List<String> getArticleClasses(String title) throws IOException{ Map<String,Object> fields = new HashMap<String,Object>(); fields.put("action", "query"); fields.put("prop","categories"); fields.put("format","json"); fields.put("cllimit","100"); fields.put("titles",title); HttpResponse<JsonNode> resp; try { try { resp = Unirest.post(this.baseURL + "/api.php") .fields(fields) .asJson(); } catch (UnirestException ex) { throw new IOException(ex); } JsonNode body = resp.getBody(); JSONObject bodyObject = body.getObject(); if(!bodyObject.has("query")) return null; JSONObject q = bodyObject.getJSONObject("query"); JSONObject pages = q.getJSONObject("pages"); Iterator<String> pageKeys = pages.keys(); while(pageKeys.hasNext()){ JSONObject page = pages.getJSONObject(pageKeys.next()); if(!page.getString("title").equals(title)) continue; /* * Got the correct key (There should only be a single key anyway) */ if(!page.has("categories")) break; JSONArray categories = page.getJSONArray("categories"); List<String> categoryList = new ArrayList<String>(); for (int i = 0; i < categories.length(); i++) { JSONObject category = categories.getJSONObject(i); categoryList.add(category.getString("title")); } return categoryList; } } catch (JSONException jse) { jse.printStackTrace(); log(jse.getMessage()); } return null; }
Example 17
Source File: MediaWikiAPIPageExtractor.java From wandora with GNU General Public License v3.0 | 4 votes |
private HashMap<String,String> getArticleInfo(String title) throws IOException{ Map<String,Object> fields = new HashMap<String,Object>(); fields.put("action", "query"); fields.put("prop","info"); fields.put("format","json"); fields.put("inprop","url"); fields.put("titles",title); HttpResponse<JsonNode> resp; try { HashMap<String,String> info = new HashMap<String, String>(); try { resp = Unirest.post(this.baseURL + "/api.php") .fields(fields) .asJson(); } catch (UnirestException ex) { throw new IOException(ex); } JsonNode body = resp.getBody(); JSONObject bodyObject = body.getObject(); if(!bodyObject.has("query")) return null; JSONObject q = bodyObject.getJSONObject("query"); JSONObject pages = q.getJSONObject("pages"); Iterator<String> pageKeys = pages.keys(); while(pageKeys.hasNext()){ JSONObject page = pages.getJSONObject(pageKeys.next()); if(!page.getString("title").equals(title)) continue; Iterator<String> valueKeys = page.keys(); while(valueKeys.hasNext()){ String key = valueKeys.next(); info.put(key, page.get(key).toString()); } return info; } } catch (JSONException jse) { jse.printStackTrace(); log(jse.getMessage()); } return null; }
Example 18
Source File: GitHubSourceConnector.java From apicurio-studio with Apache License 2.0 | 4 votes |
/** * @see io.apicurio.hub.api.connectors.ISourceConnector#updateResourceContent(java.lang.String, java.lang.String, java.lang.String, io.apicurio.hub.api.beans.ResourceContent) */ @Override public String updateResourceContent(String repositoryUrl, String commitMessage, String commitComment, ResourceContent content) throws SourceConnectorException { try { String b64Content = Base64.encodeBase64String(content.getContent().getBytes(StandardCharsets.UTF_8)); GitHubResource resource = resolver.resolve(repositoryUrl); GitHubUpdateFileRequest requestBody = new GitHubUpdateFileRequest(); requestBody.setMessage(commitMessage); requestBody.setContent(b64Content); requestBody.setSha(content.getSha()); requestBody.setBranch(resource.getBranch()); String createContentUrl = this.endpoint("/repos/:org/:repo/contents/:path") .bind("org", resource.getOrganization()) .bind("repo", resource.getRepository()) .bind("path", resource.getResourcePath()) .toString(); HttpRequestWithBody request = Unirest.put(createContentUrl).header("Content-Type", "application/json; charset=utf-8"); addSecurityTo(request); HttpResponse<JsonNode> response = request.body(requestBody).asJson(); if (response.getStatus() != 200) { throw new UnirestException("Unexpected response from GitHub: " + response.getStatus() + "::" + response.getStatusText()); } JsonNode node = response.getBody(); String newSha = node.getObject().getJSONObject("content").getString("sha"); if (commitComment != null && !commitComment.trim().isEmpty()) { String commitSha = node.getObject().getJSONObject("commit").getString("sha"); this.addCommitComment(repositoryUrl, commitSha, commitComment); } return newSha; } catch (UnirestException e) { logger.error("Error updating Github resource content.", e); throw new SourceConnectorException("Error updating Github resource content.", e); } }
Example 19
Source File: BaseTest.java From blueocean-plugin with MIT License | 4 votes |
public <T> T build(Class<T> clzzz) { HttpResponse<T> response = execute(clzzz); Assert.assertEquals(expectedStatus, response.getStatus()); return response.getBody(); }
Example 20
Source File: HttpBasedClient.java From zeppelin with Apache License 2.0 | 4 votes |
private boolean containsAggs(HttpResponse<JsonNode> result) { return result.getBody() != null && (result.getBody().getObject().has("aggregations") || result.getBody().getObject().has("aggs")); }