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:org.jspare.jsdbc.JsdbcTransportImpl.java
@Override public String execute(DataSource datasource, Credential credential, Optional<Domain> domain, String operation, int method, String data) throws JsdbcException { if (datasource == null) { throw new JsdbcException("DataSource not loaded"); }//from w ww.j ava 2s . c om try { Request request = null; org.apache.http.client.fluent.Response response = null; String uriAddress = getUrlConnection(datasource, operation, Optional.of(domain.orElse(Domain.of(StringUtils.EMPTY)).domain())); if (method == RETRIEVE) { request = Request.Get(new URIBuilder(uriAddress).build().toString()); } else if (method == SEND) { request = Request.Post(new URIBuilder(uriAddress).build().toString()).bodyString(data, ContentType.APPLICATION_JSON); } else { throw new JsdbcException("Method called is not mapped"); } request.addHeader(AGENT_KEY, AGENT); response = buildAuthentication(request, datasource, credential).execute(); HttpResponse httpResponse = response.returnResponse(); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode < HttpStatus.SC_OK || statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) { if (statusCode == HttpStatus.SC_BAD_REQUEST) { throw new JsdbcException("Authorization error, validate your credentials."); } if (statusCode == HttpStatus.SC_FORBIDDEN) { throw new JsdbcException("Forbidden access, validate your user roles."); } String content = IOUtils.toString(httpResponse.getEntity().getContent()); ErrorResult result = my(Serializer.class).fromJSON(content, ErrorResult.class); throw new CommandFailException(result); } return IOUtils.toString(httpResponse.getEntity().getContent()); } catch (Exception e) { log.error(e.getMessage(), e); throw new JsdbcException("JSDB Server Error"); } }
From source file:io.github.jonestimd.neo4j.client.http.ApacheHttpDriver.java
public HttpResponse post(String uri, String jsonEntity) throws IOException { HttpPost post = new HttpPost(uri); StringEntity entity = new StringEntity(jsonEntity); entity.setContentType(ContentType.APPLICATION_JSON.toString()); post.setEntity(entity);/*from ww w . j av a 2 s .co m*/ return new ResponseAdapter(client.execute(post, clientContext)); }
From source file:org.elasticsearch.client.RequestLoggerTests.java
public void testTraceRequest() throws IOException, URISyntaxException { HttpHost host = new HttpHost("localhost", 9200, randomBoolean() ? "http" : "https"); String expectedEndpoint = "/index/type/_api"; URI uri;/*from www.j ava 2 s.c o m*/ if (randomBoolean()) { uri = new URI(expectedEndpoint); } else { uri = new URI("index/type/_api"); } HttpUriRequest request = randomHttpRequest(uri); String expected = "curl -iX " + request.getMethod() + " '" + host + expectedEndpoint + "'"; boolean hasBody = request instanceof HttpEntityEnclosingRequest && randomBoolean(); String requestBody = "{ \"field\": \"value\" }"; if (hasBody) { expected += " -d '" + requestBody + "'"; HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request; HttpEntity entity; switch (randomIntBetween(0, 4)) { case 0: entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); break; case 1: entity = new InputStreamEntity( new ByteArrayInputStream(requestBody.getBytes(StandardCharsets.UTF_8)), ContentType.APPLICATION_JSON); break; case 2: entity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON); break; case 3: entity = new NByteArrayEntity(requestBody.getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_JSON); break; case 4: // Evil entity without a charset entity = new StringEntity(requestBody, ContentType.create("application/json", (Charset) null)); break; default: throw new UnsupportedOperationException(); } enclosingRequest.setEntity(entity); } String traceRequest = RequestLogger.buildTraceRequest(request, host); assertThat(traceRequest, equalTo(expected)); if (hasBody) { //check that the body is still readable as most entities are not repeatable String body = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity(), StandardCharsets.UTF_8); assertThat(body, equalTo(requestBody)); } }
From source file:org.modeshape.jcr.index.elasticsearch.client.EsClient.java
/** * Creates new index./* w w w. ja v a 2s .c o m*/ * * @param name the name of the index to test. * @param type index type * @param mappings field mapping definition. * @return true if index was created. * @throws IOException communication exception. */ public boolean createIndex(String name, String type, EsRequest mappings) throws IOException { if (indexExists(name)) { deleteIndex(name); } CloseableHttpClient client = HttpClients.createDefault(); HttpPost method = new HttpPost(String.format("http://%s:%d/%s", host, port, name)); try { StringEntity requestEntity = new StringEntity(mappings.toString(), ContentType.APPLICATION_JSON); method.setEntity(requestEntity); CloseableHttpResponse resp = client.execute(method); return resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } finally { method.releaseConnection(); } }
From source file:com.microfocus.application.automation.tools.octane.actions.PluginActions.java
public void doDynamic(StaplerRequest req, StaplerResponse res) throws IOException { if (req.getRequestURI().toLowerCase().contains(STATUS_REQUEST)) { JSONObject result = getStatusResult(); res.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType()); res.setStatus(200);/*ww w . j av a2s.c om*/ res.getWriter().write(result.toString()); return; } else { res.setStatus(404); res.getWriter().write(""); return; } }
From source file:com.twitter.heron.integration_test.core.AggregatorBolt.java
private int postResultToHttpServer(String newHttpPostUrl, String resultJson) throws IOException, ParseException { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(newHttpPostUrl); StringEntity requestEntity = new StringEntity(resultJson, ContentType.APPLICATION_JSON); post.setEntity(requestEntity);//from w w w . ja v a2s. c o m HttpResponse response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 200) { LOG.info("Http post successful"); } else { LOG.severe(String.format("Http post failed, response code: %d, response: %s", responseCode, EntityUtils.toString(response.getEntity()))); } return responseCode; }
From source file:se.curity.examples.oauth.opaque.OpaqueTokenValidator.java
protected String introspect(String token) throws IOException { HttpPost post = new HttpPost(_introspectionUri); post.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("token", token)); params.add(new BasicNameValuePair("client_id", _clientId)); params.add(new BasicNameValuePair("client_secret", _clientSecret)); post.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = _httpClient.execute(post); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { _logger.error("Got error from introspection server: " + response.getStatusLine().getStatusCode()); throw new IOException( "Got error from introspection server: " + response.getStatusLine().getStatusCode()); }//from ww w. jav a 2 s . c om return EntityUtils.toString(response.getEntity(), Charsets.UTF_8); }
From source file:org.elasticsearch.backwards.IndexingIT.java
private void updateIndexSetting(String name, Settings settings) throws IOException { assertOK(client().performRequest("PUT", name + "/_settings", Collections.emptyMap(), new StringEntity(Strings.toString(settings), ContentType.APPLICATION_JSON))); }
From source file:com.gooddata.http.client.LoginSSTRetrievalStrategy.java
@Override public String obtainSst(final HttpClient httpClient, final HttpHost httpHost) throws IOException { notNull(httpClient, "client can't be null"); notNull(httpHost, "host can't be null"); log.debug("Obtaining SST"); final HttpPost postLogin = new HttpPost(LOGIN_URL); try {/*from ww w. j ava 2 s.com*/ final HttpEntity requestEntity = new StringEntity(createLoginJson(), ContentType.APPLICATION_JSON); postLogin.setEntity(requestEntity); postLogin.setHeader(HttpHeaders.ACCEPT, YAML_CONTENT_TYPE); final HttpResponse response = httpClient.execute(httpHost, postLogin); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { final Header requestIdHeader = response.getFirstHeader(X_GDC_REQUEST_HEADER_NAME); final HttpEntity responseEntity = response.getEntity(); final String message = format( "Unable to login reason='%s'. Request tracking details httpStatus=%s requestId=%s", getReason(responseEntity), status, getRequestId(requestIdHeader)); log.info(message); throw new GoodDataAuthException(message); } return TokenUtils.extractToken(response); } finally { postLogin.reset(); } }
From source file:org.aksw.simba.cetus.fox.FoxBasedTypeSearcher.java
@Override public TypedNamedEntity getAllTypes(Document document, NamedEntity ne, List<ExtendedTypedNamedEntity> surfaceForms) { TypedNamedEntity tne = new TypedNamedEntity(ne.getStartPosition(), ne.getLength(), ne.getUris(), new HashSet<String>()); for (ExtendedTypedNamedEntity surfaceForm : surfaceForms) { tne.getTypes().addAll(surfaceForm.getUris()); }//from w w w . jav a2 s .c o m try { // request FOX Response response = Request.Post(FOX_SERVICE).addHeader("Content-type", "application/json") .addHeader("Accept-Charset", "UTF-8") .body(new StringEntity(new JSONObject().put("input", document.getText()).put("type", "text") .put("task", "ner").put("output", "JSON-LD").toString(), ContentType.APPLICATION_JSON)) .execute(); HttpResponse httpResponse = response.returnResponse(); HttpEntity entry = httpResponse.getEntity(); String content = IOUtils.toString(entry.getContent(), "UTF-8"); EntityUtils.consume(entry); // parse results JSONObject outObj = new JSONObject(content); if (outObj.has("@graph")) { JSONArray graph = outObj.getJSONArray("@graph"); for (int i = 0; i < graph.length(); i++) { parseType(graph.getJSONObject(i), tne, surfaceForms); } } else { parseType(outObj, tne, surfaceForms); } } catch (Exception e) { LOGGER.error("Got an exception while communicating with the FOX web service.", e); } return tne; }