List of usage examples for org.apache.http.entity ContentType create
public static ContentType create(String str, String str2) throws UnsupportedCharsetException
From source file:com.example.restexpmongomvn.controller.VehicleControllerTest.java
/** * Test of create method, of class VehicleController. * * @throws java.io.IOException//w ww . ja v a 2s .c o m */ @Test public void testCreate() throws IOException { System.out.println("create"); Vehicle testVehicle = new Vehicle(2015, "Test", "Vehicle", Color.Red, "4-Door Sedan"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Include.NON_EMPTY); String testVehicleString = objectMapper.writeValueAsString(testVehicle); // System.out.println(testVehicleString); StringEntity postEntity = new StringEntity(testVehicleString, ContentType.create("application/json", "UTF-8")); postEntity.setChunked(true); // System.out.println(postEntity.getContentType()); // System.out.println(postEntity.getContentLength()); // System.out.println(EntityUtils.toString(postEntity)); // System.out.println(EntityUtils.toByteArray(postEntity).length); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(BASE_URL + "/restexpress/vehicles"); httppost.setEntity(postEntity); CloseableHttpResponse response = httpclient.execute(httppost); String responseString = new BasicResponseHandler().handleResponse(response); assertEquals(parseMongoId(responseString), true); }
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 w ww. j av a 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.jenkinsci.plugins.appio.service.AppioService.java
/** * @param appName//from w w w . j a v a 2 s . c o m * @return AppioAppObject (org.jenkinsci.plugins.appio.model.AppioAppObject) * @throws Exception */ public AppioAppObject createApp(String appName) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); ResponseHandler<String> handler = new BasicResponseHandler(); AppioAppObject theAppObject = new AppioAppObject(); try { // App.io Authorization and Content-Type headers String appioAuth = "Basic " + apiKey; httpPost.addHeader("Authorization", appioAuth); httpPost.addHeader("Content-Type", "application/json"); httpPost.addHeader("Accept", appio_v1); // Create App.io App object AppioAppObject appioAppObj = new AppioAppObject(); appioAppObj.setName(appName); // We want to exclude all non-annotated fields Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); // Construct {"app": ... } message body AppioApp theApp = new AppioApp(); theApp.setApp(appioAppObj); StringEntity postBody = new StringEntity(gson.toJson(theApp), ContentType.create("application/json", "UTF-8")); httpPost.setEntity(postBody); LOGGER.fine("AppioService.createApp() Request: " + gson.toJson(theApp)); // Call App.io REST API to create the new app HttpResponse response = httpClient.execute(httpHost, httpPost); String jsonAppioApp = handler.handleResponse(response); LOGGER.fine("AppioService.createApp() Response: " + jsonAppioApp); // Get JSON data from the HTTP Response AppioApp appioApp = new Gson().fromJson(jsonAppioApp, AppioApp.class); theAppObject = appioApp.getApp(); } catch (Exception e) { throw e; } finally { try { httpClient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } return theAppObject; }
From source file:com.mycompany.kerberosbyip.NewMain.java
protected HttpEntity createEntity(final String requestDocAsString) { return new StringEntity(requestDocAsString, ContentType.create("application/soap+xml", "UTF-8")); }
From source file:msgclient.ServerConnection.java
public JSONObject makePostToServer(String path, String json_data) { CloseableHttpResponse response;//w w w .jav a 2s.c om JSONObject jsonObject = null; // Send a POST request to the server try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { // Create a URI URI uri = new URIBuilder().setScheme(PROTOCOL_TYPE).setHost(mServerName + ":" + mPort).setPath(path) .build(); HttpPost httppost = new HttpPost(uri); //System.out.println(httppost.getURI()); StringEntity entity = new StringEntity(json_data, ContentType.create("plain/text", "UTF-8")); entity.setContentType("application/json"); httppost.setEntity(entity); response = httpClient.execute(httppost); if (response.getStatusLine().getStatusCode() == 200) { String jsonData = IOUtils.toString(response.getEntity().getContent()); JSONParser parser = new JSONParser(); Object obj = parser.parse(jsonData); jsonObject = (JSONObject) obj; } else { System.out.println( "Received status code " + response.getStatusLine().getStatusCode() + " from server"); } response.close(); httpClient.close(); } catch (Exception e) { System.out.println(e); return null; } return jsonObject; }
From source file:org.ldp4j.server.IntegrationTestHelper.java
public void executeCommand(Object command) throws Exception { HttpPost post = new HttpPost(resolve("ldp4j/action/")); post.setHeader(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN); post.setEntity(new StringEntity(commandUtil.toString(CommandDescription.newInstance(command)), ContentType.create(Command.MIME, "UTF-8"))); httpRequest(post);/* w w w. j av a 2s. co m*/ }
From source file:org.metaservice.core.AbstractDispatcher.java
protected void sendDataByLoad(URI metadata, Collection<Statement> generatedStatements, Set<Statement> loadedStatements) throws MetaserviceException { StringWriter stringWriter = new StringWriter(); try {/*from w ww. ja v a 2 s.co m*/ NTriplesWriter nTriplesWriter = new NTriplesWriter(stringWriter); Repository inferenceRepository = createTempRepository(true); RepositoryConnection inferenceRepositoryConnection = inferenceRepository.getConnection(); LOGGER.debug("Start inference..."); inferenceRepositoryConnection.add(loadedStatements); inferenceRepositoryConnection.add(generatedStatements); LOGGER.debug("Finished inference"); List<Statement> filteredStatements = getGeneratedStatements(inferenceRepositoryConnection, loadedStatements); nTriplesWriter.startRDF(); for (Statement statement : filteredStatements) { nTriplesWriter.handleStatement(statement); } nTriplesWriter.endRDF(); inferenceRepositoryConnection.close(); inferenceRepository.shutDown(); Executor executor = Executor.newInstance(HttpClientBuilder.create() .setConnectionManager(new BasicHttpClientConnectionManager()).build()); executor.execute(Request.Post(config.getSparqlEndpoint() + "?context-uri=" + metadata.toString()) .bodyStream(new ByteArrayInputStream(stringWriter.getBuffer().toString().getBytes("UTF-8")), ContentType.create("text/plain", Charset.forName("UTF-8")))); } catch (RDFHandlerException | IOException | RepositoryException e) { throw new MetaserviceException(e); } }
From source file:com.seleritycorp.common.base.http.client.HttpResponseTest.java
private HttpResponse createHttpResponse(int status, byte[] body, Charset charset) throws Exception { StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, status, "ReasonFoo"); org.apache.http.HttpResponse backendResponse = new BasicHttpResponse(statusLine); if (body != null) { backendResponse.setEntity(new ByteArrayEntity(body, ContentType.create("foo", charset))); }//w ww . ja v a 2 s. c o m return new HttpResponse(backendResponse); }
From source file:edu.jhuapl.dorset.http.apache.ApacheHttpClient.java
private Response put(HttpRequest request) throws IOException { Request apacheRequest = Request.Put(request.getUrl()); if (request.getBody() != null) { ContentType ct = ContentType.create(request.getContentType().getMimeType(), request.getContentType().getCharset()); apacheRequest.bodyString(request.getBody(), ct); } else if (request.getBodyForm() != null) { apacheRequest.bodyForm(buildFormBody(request.getBodyForm())); }/*from ww w . j ava 2 s .co m*/ prepareRequest(apacheRequest); return apacheRequest.execute(); }
From source file:org.carewebframework.vista.api.mbroker.BrokerResponse.java
/** * Parse the returned content type.// w w w .j av a 2s. c o m * * @param value Value to parse * @return ContentType instance */ private ContentType parseContentType(String value) { String[] pcs = value.split("\\;"); String mimeType = pcs[0].trim(); String charSet = "UTF-8"; for (int i = 1; i < pcs.length; i++) { String s = pcs[i].trim().toUpperCase(); if (s.startsWith("CHARSET=")) { charSet = s.substring(8); break; } } return ContentType.create(mimeType, charSet); }