com.mashape.unirest.request.HttpRequestWithBody Java Examples
The following examples show how to use
com.mashape.unirest.request.HttpRequestWithBody.
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: TelegramBot.java From JavaTelegramBot-API with GNU General Public License v3.0 | 6 votes |
/** * Use this method to get a new TelegramBot instance with the selected auth token * * @param authToken The bots auth token * * @return A new TelegramBot instance or null if something failed */ public static TelegramBot login(String authToken) { try { HttpRequestWithBody request = Unirest.post(API_URL + "bot" + authToken + "/getMe"); HttpResponse<String> response = request.asString(); JSONObject jsonResponse = Utils.processResponse(response); if (jsonResponse != null && Utils.checkResponseStatus(jsonResponse)) { JSONObject result = jsonResponse.getJSONObject("result"); return new TelegramBot(authToken, result.getInt("id"), result.getString("first_name"), result.getString("username")); } } catch (UnirestException e) { e.printStackTrace(); } return null; }
Example #2
Source File: HttpApiServiceImpl.java From pagerduty-client with MIT License | 6 votes |
public EventResult notifyEvent(Incident incident) throws NotifyEventException { try { HttpRequestWithBody request = Unirest.post(eventApi) .header("Accept", "application/json"); request.body(incident); HttpResponse<JsonNode> jsonResponse = request.asJson(); log.debug(IOUtils.toString(jsonResponse.getRawBody())); switch(jsonResponse.getStatus()) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: return EventResult.successEvent(JsonUtils.getPropertyValue(jsonResponse, "status"), JsonUtils.getPropertyValue(jsonResponse, "message"), JsonUtils.getPropertyValue(jsonResponse, "dedup_key")); case HttpStatus.SC_BAD_REQUEST: return EventResult.errorEvent(JsonUtils.getPropertyValue(jsonResponse, "status"), JsonUtils.getPropertyValue(jsonResponse, "message"), JsonUtils.getArrayValue(jsonResponse, "errors")); default: return EventResult.errorEvent(String.valueOf(jsonResponse.getStatus()), "", IOUtils.toString(jsonResponse.getRawBody())); } } catch (UnirestException | IOException e) { throw new NotifyEventException(e); } }
Example #3
Source File: RestAction.java From cognitivej with Apache License 2.0 | 6 votes |
private T doWork() { try { setupErrorHandlers(); WorkingContext workingContext = workingContext(); HttpRequest builtRequest = buildUnirest(workingContext) .queryString(workingContext.getQueryParams()) .headers(workingContext.getHeaders()).header("Ocp-Apim-Subscription-Key", cognitiveContext.subscriptionKey); if (!workingContext.getHttpMethod().equals(HttpMethod.GET) && workingContext().getPayload().size() > 0) { buildBody((HttpRequestWithBody) builtRequest); } HttpResponse response; if (typedResponse() == InputStream.class) response = builtRequest.asBinary(); else response = builtRequest.asString(); checkForError(response); return postProcess(typeResponse(response.getBody())); } catch (UnirestException | IOException e) { throw new CognitiveException(e); } }
Example #4
Source File: GitHubSourceConnector.java From apicurio-studio with Apache License 2.0 | 6 votes |
/** * Uses the GH API to add a commit comment. * @param repositoryUrl * @param commitSha * @param commitComment * @throws UnirestException * @throws SourceConnectorException */ private void addCommitComment(String repositoryUrl, String commitSha, String commitComment) throws UnirestException, SourceConnectorException { GitHubCreateCommitCommentRequest body = new GitHubCreateCommitCommentRequest(); body.setBody(commitComment); GitHubResource resource = resolver.resolve(repositoryUrl); String addCommentUrl = this.endpoint("/repos/:org/:repo/commits/:sha/comments") .bind("org", resource.getOrganization()) .bind("repo", resource.getRepository()) .bind("path", resource.getResourcePath()) .bind("sha", commitSha) .toString(); HttpRequestWithBody request = Unirest.post(addCommentUrl).header("Content-Type", "application/json; charset=utf-8"); addSecurityTo(request); HttpResponse<JsonNode> response = request.body(body).asJson(); if (response.getStatus() != 201) { throw new UnirestException("Unexpected response from GitHub: " + response.getStatus() + "::" + response.getStatusText()); } }
Example #5
Source File: AbstractRequest.java From alpaca-java with MIT License | 6 votes |
/** * Invoke post. * * @param abstractRequestBuilder the abstract request builder * * @return the http response */ public HttpResponse<InputStream> invokePost(AbstractRequestBuilder abstractRequestBuilder) { try { String url = abstractRequestBuilder.getURL(); LOGGER.debug("POST URL: " + url); HttpRequestWithBody request = Unirest.post(url); if (!headers.isEmpty()) { request.headers(headers); LOGGER.debug("POST Headers: " + headers); } String body = abstractRequestBuilder.getBody(); if (body != null) { request.body(body); LOGGER.debug("POST Body: " + body); } return request.asBinary(); } catch (UnirestException e) { LOGGER.error("UnirestException", e); } return null; }
Example #6
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 #7
Source File: AppServicePacketTransport.java From swellrt with Apache License 2.0 | 5 votes |
private BaseRequest formRequest(Request packet) { HttpRequest httpRequest = null; String url = "https://" + serverAddress + apiAddress + packet.getUrl(); String method = packet.getMethod(); switch (method) { case "GET": httpRequest = Unirest.get(url); break; case "POST": httpRequest = Unirest.post(url); break; case "PUT": httpRequest = Unirest.put(url); break; } Map<String, String> headers = packet.getHeaders(); httpRequest = httpRequest.headers(headers); Map<String, Object> queryStrings = packet.getQueryStrings(); httpRequest = httpRequest.queryString(queryStrings); BaseRequest request = httpRequest; if(!method.equals("GET")) { JSONObject body = packet.getBody(); request = ((HttpRequestWithBody)request).body(body.toString()); } return request; }
Example #8
Source File: UnirestDownloader.java From gecco with MIT License | 5 votes |
@Override public HttpResponse download(HttpRequest request) throws DownloaderException { if(log.isDebugEnabled()) { log.debug("downloading..." + request.getUrl()); } try { HttpHost proxy = Proxys.getProxy(); if(proxy != null) { Unirest.setProxy(proxy); } else { Unirest.setProxy(null); } request.addHeader("User-Agent", UserAgent.getUserAgent()); com.mashape.unirest.http.HttpResponse<String> response = null; if(request instanceof HttpPostRequest) { HttpPostRequest post = (HttpPostRequest)request; HttpRequestWithBody httpRequestWithBody = Unirest.post(post.getUrl()); httpRequestWithBody.headers(post.getHeaders()); httpRequestWithBody.fields(post.getFields()); response = httpRequestWithBody.asString(); } else { response = Unirest.get(request.getUrl()).headers(request.getHeaders()).asString(); } String contentType = response.getHeaders().getFirst("Content-Type"); HttpResponse resp = new HttpResponse(); resp.setStatus(response.getStatus()); resp.setRaw(response.getRawBody()); resp.setContent(response.getBody()); resp.setContentType(contentType); resp.setCharset(getCharset(request, contentType)); return resp; } catch (UnirestException e) { throw new DownloaderException(e); } }
Example #9
Source File: MicrocksConnector.java From apicurio-studio with Apache License 2.0 | 5 votes |
/** * Returns the OAuth token to use when accessing Microcks. * * @throws MicrocksConnectorException */ private String getKeycloakOAuthToken() throws MicrocksConnectorException { String keycloakURL = getKeycloakURL(); String keycloakClientId = config.getMicrocksClientId(); String keycloakClientSecret = config.getMicrocksClientSecret(); // Retrieve a token using client_credentials flow. HttpRequestWithBody tokenRequest = Unirest.post(keycloakURL + "/protocol/openid-connect/token") .header("Content-Type", "application/x-www-form-urlencoded") .header("Accept", "application/json").basicAuth(keycloakClientId, keycloakClientSecret); HttpResponse<JsonNode> tokenResponse = null; try { tokenResponse = tokenRequest.body("grant_type=client_credentials").asJson(); } catch (UnirestException e) { logger.error("Exception while connecting to Keycloak backend", e); throw new MicrocksConnectorException( "Exception while connecting Microcks Keycloak backend. Check Keycloak configuration."); } if (tokenResponse.getStatus() != 200) { logger.error( "OAuth token cannot be retrieved for Microcks server, check keycloakClient configuration"); throw new MicrocksConnectorException( "OAuth token cannot be retrieved for Microcks. Check keycloakClient."); } return tokenResponse.getBody().getObject().getString("access_token"); }
Example #10
Source File: GitHubSourceConnector.java From apicurio-studio with Apache License 2.0 | 5 votes |
/** * @see io.apicurio.hub.api.connectors.ISourceConnector#createResourceContent(java.lang.String, java.lang.String, java.lang.String) */ @Override public void createResourceContent(String repositoryUrl, String commitMessage, String content) throws SourceConnectorException { try { String b64Content = Base64.encodeBase64String(content.getBytes(StandardCharsets.UTF_8)); GitHubResource resource = resolver.resolve(repositoryUrl); GitHubCreateFileRequest requestBody = new GitHubCreateFileRequest(); requestBody.setMessage(commitMessage); requestBody.setContent(b64Content); 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<InputStream> response = request.body(requestBody).asBinary(); if (response.getStatus() != 201) { throw new UnirestException("Unexpected response from GitHub: " + response.getStatus() + "::" + response.getStatusText()); } } catch (UnirestException e) { logger.error("Error creating Github resource content.", e); throw new SourceConnectorException("Error creating Github resource content.", e); } }
Example #11
Source File: RestAction.java From cognitivej with Apache License 2.0 | 5 votes |
private void buildBody(HttpRequestWithBody builtRequest) throws IOException { if (workingContext().getPayload().containsKey(IMAGE_INPUT_STREAM_KEY)) { builtRequest.header("content-type", "application/octet-stream").body(IOUtils.toByteArray((InputStream) workingContext().getPayload().get(IMAGE_INPUT_STREAM_KEY))); } else { builtRequest.header("content-type", "application/json").body(new JSONObject(workingContext().getPayload())); } }
Example #12
Source File: PacketBuilder.java From discord.jar with The Unlicense | 5 votes |
public String makeRequest() { try { HttpRequestWithBody request; switch (type) { case DELETE: request = Unirest.delete(url); break; case OPTIONS: request = Unirest.options(url); break; case PATCH: request = Unirest.patch(url); break; case POST: request = Unirest.post(url); break; case PUT: request = Unirest.put(url); break; case GET: return Unirest.get(url).header("authorization", "Bot " + api.getLoginTokens().getToken()).header("Content-Type", isForm ? "application/x-www-form-urlencoded" : (file ? "application/octet-stream" : "application/json; charset=utf-8")).asString().getBody(); default: throw new RuntimeException(); } return request.header("authorization", "Bot " + api.getLoginTokens().getToken()).header("Content-Type", isForm ? "application/x-www-form-urlencoded" : (file ? "application/octet-stream" : "application/json; charset=utf-8")).body(data).asString().getBody(); } catch (UnirestException e) { throw new RuntimeException(e); } }
Example #13
Source File: AbstractRequest.java From alpaca-java with MIT License | 5 votes |
/** * Invoke options. * * @param abstractRequestBuilder the abstract request builder * * @return the http response */ public HttpResponse<InputStream> invokeOptions(AbstractRequestBuilder abstractRequestBuilder) { try { String url = abstractRequestBuilder.getURL(); LOGGER.debug("OPTIONS URL " + url); HttpRequestWithBody request = Unirest.options(url); if (!headers.isEmpty()) { request.headers(headers); LOGGER.debug("OPTIONS Headers: " + headers); } String body = abstractRequestBuilder.getBody(); if (body != null) { request.body(body); LOGGER.debug("OPTIONS Body: " + body); } return request.asBinary(); } catch (UnirestException e) { LOGGER.error("UnirestException", e); } return null; }
Example #14
Source File: AbstractRequest.java From alpaca-java with MIT License | 5 votes |
/** * Invoke delete. * * @param abstractRequestBuilder the abstract request builder * * @return the http response */ public HttpResponse<InputStream> invokeDelete(AbstractRequestBuilder abstractRequestBuilder) { try { String url = abstractRequestBuilder.getURL(); LOGGER.debug("DELETE URL " + url); HttpRequestWithBody request = Unirest.delete(url); if (!headers.isEmpty()) { request.headers(headers); LOGGER.debug("DELETE Headers: " + headers); } String body = abstractRequestBuilder.getBody(); if (body != null) { request.body(body); LOGGER.debug("DELETE Body: " + body); } return request.asBinary(); } catch (UnirestException e) { LOGGER.error("UnirestException", e); } return null; }
Example #15
Source File: AbstractRequest.java From alpaca-java with MIT License | 5 votes |
/** * Invoke put http response. * * @param abstractRequestBuilder the abstract request builder * * @return the http response */ public HttpResponse<InputStream> invokePut(AbstractRequestBuilder abstractRequestBuilder) { try { String url = abstractRequestBuilder.getURL(); LOGGER.debug("PUT URL " + url); HttpRequestWithBody request = Unirest.put(url); if (!headers.isEmpty()) { request.headers(headers); LOGGER.debug("PUT Headers: " + headers); } String body = abstractRequestBuilder.getBody(); if (body != null) { request.body(body); LOGGER.debug("PUT Body: " + body); } return request.asBinary(); } catch (UnirestException e) { LOGGER.error("UnirestException", e); } return null; }
Example #16
Source File: AbstractRequest.java From alpaca-java with MIT License | 5 votes |
/** * Invoke patch. * * @param abstractRequestBuilder the abstract request builder * * @return the http response */ public HttpResponse<InputStream> invokePatch(AbstractRequestBuilder abstractRequestBuilder) { try { String url = abstractRequestBuilder.getURL(); LOGGER.debug("PATCH URL " + url); HttpRequestWithBody request = Unirest.patch(url); if (!headers.isEmpty()) { request.headers(headers); LOGGER.debug("PATCH Headers: " + headers); } String body = abstractRequestBuilder.getBody(); if (body != null) { request.body(body); LOGGER.debug("PATCH Body: " + body); } return request.asBinary(); } catch (UnirestException e) { LOGGER.error("UnirestException", e); } return null; }
Example #17
Source File: Unirest.java From unirest-android with MIT License | 4 votes |
public static HttpRequestWithBody put(String url) { return new HttpRequestWithBody(HttpMethod.PUT, url); }
Example #18
Source File: Unirest.java From unirest-android with MIT License | 4 votes |
public static HttpRequestWithBody patch(String url) { return new HttpRequestWithBody(HttpMethod.PATCH, url); }
Example #19
Source File: Unirest.java From unirest-android with MIT License | 4 votes |
public static HttpRequestWithBody delete(String url) { return new HttpRequestWithBody(HttpMethod.DELETE, url); }
Example #20
Source File: Unirest.java From unirest-android with MIT License | 4 votes |
public static HttpRequestWithBody post(String url) { return new HttpRequestWithBody(HttpMethod.POST, url); }
Example #21
Source File: BaseTestCase.java From blade with Apache License 2.0 | 4 votes |
protected HttpRequestWithBody post(String path) { log.info("[POST] {}", (origin + path)); return Unirest.post(origin + path); }
Example #22
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 #23
Source File: RequestExecutor.java From Bastion with GNU General Public License v3.0 | 4 votes |
private void applyBody() { if (executableHttpRequest instanceof HttpRequestWithBody) { ((HttpRequestWithBody) executableHttpRequest).body(bastionHttpRequest.body().toString()); } }