List of usage examples for org.apache.http.entity ContentType APPLICATION_JSON
ContentType APPLICATION_JSON
To view the source code for org.apache.http.entity ContentType APPLICATION_JSON.
Click Source Link
From source file:io.gravitee.gateway.standalone.PostContentGatewayTest.java
@Test public void call_case2_chunked() throws Exception { String testCase = "case2"; InputStream is = this.getClass().getClassLoader().getResourceAsStream(testCase + "/request_content.json"); Request request = Request.Post("http://localhost:8082/test/my_team?case=" + testCase).bodyStream(is, ContentType.APPLICATION_JSON); try {//from w ww . j a va 2 s . c o m Response response = request.execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); assertEquals(HttpHeadersValues.TRANSFER_ENCODING_CHUNKED, returnResponse.getFirstHeader(HttpHeaders.TRANSFER_ENCODING).getValue()); String responseContent = StringUtils.copy(returnResponse.getEntity().getContent()); assertEquals(652051, responseContent.length()); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } }
From source file:com.hp.mqm.clt.TestSupportClient.java
private JSONObject postEntity(String uri, JSONObject entityObject) throws IOException { URI requestURI = createWorkspaceApiUri(uri); HttpPost request = new HttpPost(requestURI); JSONArray data = new JSONArray(); data.add(entityObject);/*from ww w .j a v a 2s . c om*/ JSONObject body = new JSONObject(); body.put("data", data); request.setEntity(new StringEntity(body.toString(), ContentType.APPLICATION_JSON)); CloseableHttpResponse response = null; try { response = execute(request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { String payload = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); throw new IOException("Posting failed with status code " + response.getStatusLine().getStatusCode() + ", reason " + response.getStatusLine().getReasonPhrase() + " and payload: " + payload); } ByteArrayOutputStream result = new ByteArrayOutputStream(); response.getEntity().writeTo(result); JSONObject jsonObject = JSONObject.fromObject(new String(result.toByteArray(), "UTF-8")); return jsonObject.getJSONArray("data").getJSONObject(0); } finally { HttpClientUtils.closeQuietly(response); } }
From source file:com.ibm.watson.ta.retail.TAProxyServlet.java
/** * Create and POST a request to the Watson service * * @param req/* w w w .j ava 2s .c o m*/ * the Http Servlet request * @param resp * the Http Servlet response * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); try { String reqURI = req.getRequestURI(); String endpoint = reqURI.substring(reqURI.lastIndexOf('/') + 1); String url = baseURL + "/v1/" + endpoint; // concatenate query params String queryStr = req.getQueryString(); if (queryStr != null) { url += "?" + queryStr; } URI uri = new URI(url).normalize(); logger.info("posting to " + url); Request newReq = Request.Post(uri); newReq.addHeader("Accept", "application/json"); String metadata = req.getHeader("x-watson-metadata"); if (metadata != null) { metadata += "client-ip:" + req.getRemoteAddr(); newReq.addHeader("x-watson-metadata", metadata); } InputStreamEntity entity = new InputStreamEntity(req.getInputStream()); newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON); Executor executor = this.buildExecutor(uri); Response response = executor.execute(newReq); HttpResponse httpResponse = response.returnResponse(); resp.setStatus(httpResponse.getStatusLine().getStatusCode()); ServletOutputStream servletOutputStream = resp.getOutputStream(); httpResponse.getEntity().writeTo(servletOutputStream); servletOutputStream.flush(); servletOutputStream.close(); logger.info("post done"); } catch (Exception e) { // Log something and return an error message logger.log(Level.SEVERE, "got error: " + e.getMessage(), e); resp.setStatus(HttpStatus.SC_BAD_GATEWAY); } }
From source file:de.stklcode.jvault.connector.HTTPVaultConnectorOfflineTest.java
/** * Test exceptions thrown during request. *//* w w w . ja v a 2 s . co m*/ @Test public void requestExceptionTest() throws IOException { HTTPVaultConnector connector = new HTTPVaultConnector("http://127.0.0.1", null, 0, 250); // Test invalid response code. final int responseCode = 400; mockResponse(responseCode, "", ContentType.APPLICATION_JSON); try { connector.getHealth(); fail("Querying health status succeeded on invalid instance"); } catch (Exception e) { assertThat("Unexpected type of exception", e, instanceOf(InvalidResponseException.class)); assertThat("Unexpected exception message", e.getMessage(), is("Invalid response code")); assertThat("Unexpected status code in exception", ((InvalidResponseException) e).getStatusCode(), is(responseCode)); assertThat("Response message where none was expected", ((InvalidResponseException) e).getResponse(), is(nullValue())); } // Simulate permission denied response. mockResponse(responseCode, "{\"errors\":[\"permission denied\"]}", ContentType.APPLICATION_JSON); try { connector.getHealth(); fail("Querying health status succeeded on invalid instance"); } catch (Exception e) { assertThat("Unexpected type of exception", e, instanceOf(PermissionDeniedException.class)); } // Test exception thrown during request. when(httpMock.execute(any())).thenThrow(new IOException("Test Exception")); try { connector.getHealth(); fail("Querying health status succeeded on invalid instance"); } catch (Exception e) { assertThat("Unexpected type of exception", e, instanceOf(InvalidResponseException.class)); assertThat("Unexpected exception message", e.getMessage(), is("Unable to read response")); assertThat("Unexpected cause", e.getCause(), instanceOf(IOException.class)); } // Now simulate a failing request that succeeds on second try. connector = new HTTPVaultConnector("https://127.0.0.1", null, 1, 250); doReturn(responseMock).doReturn(responseMock).when(httpMock).execute(any()); doReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 500, "")) .doReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 500, "")) .doReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 500, "")) .doReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "")).when(responseMock) .getStatusLine(); when(responseMock.getEntity()).thenReturn(new StringEntity("{}", ContentType.APPLICATION_JSON)); try { connector.getHealth(); } catch (Exception e) { fail("Request failed unexpectedly: " + e.getMessage()); } }
From source file:nl.esciencecenter.octopus.webservice.api.SandboxedJob.java
private void putState2Callback() throws IOException { if (request != null && request.status_callback_url != null) { String body = getStatusResponse().toJson(); HttpPut put = new HttpPut(request.status_callback_url); HttpEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON); put.setEntity(entity);//from w w w .j av a2 s. c o m httpClient.execute(put); } }
From source file:com.qwazr.utils.json.client.JsonClientAbstract.java
/** * {@inheritDoc}// w w w .j ava2 s.c o m */ @Override final public <T> T execute(Request request, Object bodyObject, Integer msTimeOut, Class<T> jsonResultClass, int... expectedCodes) throws IOException { if (logger.isDebugEnabled()) logger.debug(request.toString()); if (msTimeOut == null) msTimeOut = this.timeout; request = setBodyString(request, bodyObject); JsonHttpResponseHandler.JsonValueResponse<T> responseHandler = new JsonHttpResponseHandler.JsonValueResponse<T>( ContentType.APPLICATION_JSON, jsonResultClass, expectedCodes); return executor.execute(request.connectTimeout(msTimeOut).socketTimeout(msTimeOut).addHeader("Accept", ContentType.APPLICATION_JSON.toString())).handleResponse(responseHandler); }
From source file:org.opennms.netmgt.notifd.AbstractSlackCompatibleNotificationStrategy.java
/** {@inheritDoc} */ @SuppressWarnings("unchecked") public int send(List<Argument> arguments) { m_arguments = arguments;/*from ww w .j av a 2s . c o m*/ String url = getUrl(); if (url == null) { LOG.error("send: url must not be null"); return 1; } String iconUrl = getIconUrl(); String iconEmoji = getIconEmoji(); String channel = getChannel(); String message = buildMessage(arguments); final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(3000) .setSocketTimeout(3000).useSystemProxySettings(); HttpPost postMethod = new HttpPost(url); JSONObject jsonData = new JSONObject(); jsonData.put("username", getUsername()); if (iconUrl != null) { jsonData.put("icon_url", iconUrl); } if (iconEmoji != null) { jsonData.put("icon_emoji", iconEmoji); } if (channel != null) { jsonData.put("channel", channel); } jsonData.put("text", message); if (jsonData.containsKey("icon_url") && jsonData.containsKey("icon_emoji")) { LOG.warn("Both URL and emoji specified for icon. Sending both; behavior is undefined."); } LOG.debug("Prepared JSON POST data for webhook is: {}", jsonData.toJSONString()); final HttpEntity entity = new StringEntity(jsonData.toJSONString(), ContentType.APPLICATION_JSON); postMethod.setEntity(entity); // Mattermost 1.1.0 does not like having charset specified alongside Content-Type postMethod.setHeader("Content-Type", "application/json"); String contents = null; int statusCode = -1; try { CloseableHttpResponse response = clientWrapper.getClient().execute(postMethod); statusCode = response.getStatusLine().getStatusCode(); contents = EntityUtils.toString(response.getEntity()); LOG.debug("send: Contents is: {}", contents); } catch (IOException e) { LOG.error("send: I/O problem with webhook post/response: {}", e); throw new RuntimeException("Problem with webhook post: " + e.getMessage()); } finally { IOUtils.closeQuietly(clientWrapper); } if ("ok".equals(contents)) { LOG.debug("Got 'ok' back from webhook, indicating success."); statusCode = 0; } else { LOG.info("Got a non-ok response from webhook, attempting to dissect response."); LOG.error("Webhook returned non-OK response to notification post: {}", formatWebhookErrorResponse(statusCode, contents)); statusCode = 1; } return statusCode; }
From source file:org.apache.james.jmap.methods.integration.cucumber.SetMailboxesMethodStepdefs.java
@When("^renaming mailbox \"([^\"]*)\" to \"([^\"]*)\"") public void renamingMailbox(String actualMailboxName, String newMailboxName) throws Throwable { String username = userStepdefs.lastConnectedUser; Mailbox mailbox = mainStepdefs.jmapServer.serverProbe().getMailbox("#private", userStepdefs.lastConnectedUser, actualMailboxName); String mailboxId = mailbox.getMailboxId().serialize(); String requestBody = "[" + " [ \"setMailboxes\"," + " {" + " \"update\": {" + " \"" + mailboxId + "\" : {" + " \"name\" : \"" + newMailboxName + "\"" + " }" + " }" + " }," + " \"#0\"" + " ]" + "]"; Request.Post(mainStepdefs.baseUri().setPath("/jmap").build()) .addHeader("Authorization", userStepdefs.tokenByUser.get(username).serialize()) .bodyString(requestBody, ContentType.APPLICATION_JSON).execute().discardContent(); }
From source file:com.nextdoor.bender.ipc.http.HttpTransportTest.java
@Test(expected = TransportException.class) public void testErrorsResponse() throws TransportException, IOException { byte[] respPayload = "resp".getBytes(StandardCharsets.UTF_8); HttpClient client = getMockClientWithResponse(respPayload, ContentType.APPLICATION_JSON, HttpStatus.SC_INTERNAL_SERVER_ERROR, false); HttpTransport transport = new HttpTransport(client, "", false, 1, 1); try {//from w w w. j av a2 s . co m transport.sendBatch("foo".getBytes()); } catch (Exception e) { assertEquals("http transport call failed because \"expected failure\" payload response \"resp\"", e.getCause().getMessage()); throw e; } }
From source file:org.apache.calcite.adapter.elasticsearch.EmbeddedElasticsearchPolicy.java
void insertDocument(String index, ObjectNode document) throws IOException { Objects.requireNonNull(index, "index"); Objects.requireNonNull(document, "document"); String uri = String.format(Locale.ROOT, "/%s/%s/?refresh", index, index); StringEntity entity = new StringEntity(mapper().writeValueAsString(document), ContentType.APPLICATION_JSON); restClient().performRequest("POST", uri, Collections.emptyMap(), entity); }