List of usage examples for org.apache.http.entity ContentType create
public static ContentType create(String str, String str2) throws UnsupportedCharsetException
From source file:org.n52.oxf.util.web.SimpleHttpClient.java
public HttpResponse executePost(String uri, XmlObject payloadToSend) throws HttpClientException { return executePost(uri, payloadToSend.xmlText(), ContentType.create("text/xml", Consts.UTF_8)); }
From source file:org.sasabus.export2Freegis.network.DataReadyManager.java
@Override public void handle(HttpExchange httpExchange) throws IOException { long start = System.currentTimeMillis(); BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "UTF-8")); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpExchange.getResponseBody())); try {//ww w. ja va 2 s .co m StringBuilder requestStringBuff = new StringBuilder(); int b; while ((b = in.read()) != -1) { requestStringBuff.append((char) b); } Scanner sc = new Scanner(new File(DATAACKNOWLEDGE)); String rdyackstring = ""; while (sc.hasNextLine()) { rdyackstring += sc.nextLine(); } sc.close(); SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ"); Date d = new Date(); String timestamp = date_date.format(d) + "T" + date_time.format(d); timestamp = timestamp.substring(0, timestamp.length() - 2) + ":" + timestamp.substring(timestamp.length() - 2); rdyackstring = rdyackstring.replaceAll(":timestamp", timestamp); httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, rdyackstring.length()); out.write(rdyackstring); out.flush(); long before_elab = System.currentTimeMillis() - start; DataRequestManager teqrequest = new DataRequestManager(this.hostname, this.portnumber); String datarequest = teqrequest.datarequest(); ArrayList<TeqObjects> requestelements = TeqXMLUtils.extractFromXML(datarequest); int vtcounter = 0; if (!requestelements.isEmpty()) { Iterator<TeqObjects> iterator = requestelements.iterator(); System.out.println("Sending List of Elements!"); String geoJson = "{\"type\":\"FeatureCollection\",\"features\":["; while (iterator.hasNext()) { TeqObjects object = iterator.next(); if (object instanceof VehicleTracking) { geoJson += ((VehicleTracking) object).toGeoJson() + ","; ++vtcounter; } } if (geoJson.charAt(geoJson.length() - 1) == ',') { geoJson = geoJson.substring(0, geoJson.length() - 1); } geoJson += "]}"; System.out.println( "GeoJson sent! (Nr of elements: " + vtcounter + "/" + requestelements.size() + " )"); HttpPost subrequest = new HttpPost(DATASEND); StringEntity requestEntity = new StringEntity(geoJson, ContentType.create("application/json", "UTF-8")); CloseableHttpClient httpClient = HttpClients.createDefault(); subrequest.setEntity(requestEntity); long after_elab = System.currentTimeMillis() - start; CloseableHttpResponse response = httpClient.execute(subrequest); //System.out.println("Stauts JsonSend Response: " + response.getStatusLine().getStatusCode()); //System.out.println("Status JsonSend Phrase: " + response.getStatusLine().getReasonPhrase()); httpClient.close(); long before_db = System.currentTimeMillis() - start; dbmanager.insertIntoDatabase(requestelements); System.out.format( "Thread time (ms) : Before elab: %d, After Elab (before http sending): %d, Before db: %d, Total: %d, Thread name: %s, Objects elaborated: %d", before_elab, after_elab, before_db, (System.currentTimeMillis() - start), Thread.currentThread().getName(), requestelements.size()); System.out.println(""); } } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(-1); return; } finally { if (in != null) in.close(); if (out != null) out.close(); if (httpExchange != null) httpExchange.close(); } }
From source file:com.github.tomakehurst.wiremock.http.ProxyResponseRenderer.java
private static HttpEntity buildEntityFrom(Request originalRequest) { ContentTypeHeader contentTypeHeader = originalRequest.contentTypeHeader().or("text/plain"); ContentType contentType = ContentType.create(contentTypeHeader.mimeTypePart(), contentTypeHeader.encodingPart().or("utf-8")); if (originalRequest.containsHeader(TRANSFER_ENCODING) && originalRequest.header(TRANSFER_ENCODING).firstValue().equals("chunked")) { return new InputStreamEntity(new ByteArrayInputStream(originalRequest.getBody()), -1, contentType); }/*from www .j a va2 s .c o m*/ return new ByteArrayEntity(originalRequest.getBody()); }
From source file:ch.cyberduck.core.googledrive.DriveWriteFeature.java
@Override public HttpResponseOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final DelayedHttpEntityCallable<Void> command = new DelayedHttpEntityCallable<Void>() { @Override//from w w w . j a v a 2 s. com public Void call(final AbstractHttpEntity entity) throws BackgroundException { try { final String base = session.getClient().getRootUrl(); // Initiate a resumable upload final HttpEntityEnclosingRequestBase request; if (status.isExists()) { final String fileid = new DriveFileidProvider(session).getFileid(file, new DisabledListProgressListener()); request = new HttpPatch( String.format("%s/upload/drive/v3/files/%s?supportsTeamDrives=true", base, fileid)); if (StringUtils.isNotBlank(status.getMime())) { request.setHeader(HttpHeaders.CONTENT_TYPE, status.getMime()); } // Upload the file request.setEntity(entity); } else { request = new HttpPost(String.format( String.format( "%%s/upload/drive/v3/files?uploadType=resumable&supportsTeamDrives=%s", PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")), base)); request.setEntity(new StringEntity( "{\"name\": \"" + file.getName() + "\", \"parents\": [\"" + new DriveFileidProvider(session).getFileid(file.getParent(), new DisabledListProgressListener()) + "\"]}", ContentType.create("application/json", "UTF-8"))); if (StringUtils.isNotBlank(status.getMime())) { // Set to the media MIME type of the upload data to be transferred in subsequent requests. request.addHeader("X-Upload-Content-Type", status.getMime()); } } request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE); final HttpClient client = session.getHttpClient(); final HttpResponse response = client.execute(request); try { switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: break; default: throw new DriveExceptionMappingService() .map(new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } } finally { EntityUtils.consume(response.getEntity()); } if (!status.isExists()) { if (response.containsHeader(HttpHeaders.LOCATION)) { final String putTarget = response.getFirstHeader(HttpHeaders.LOCATION).getValue(); // Upload the file final HttpPut put = new HttpPut(putTarget); put.setEntity(entity); final HttpResponse putResponse = client.execute(put); try { switch (putResponse.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: break; default: throw new DriveExceptionMappingService().map( new HttpResponseException(putResponse.getStatusLine().getStatusCode(), putResponse.getStatusLine().getReasonPhrase())); } } finally { EntityUtils.consume(putResponse.getEntity()); } } else { throw new DriveExceptionMappingService() .map(new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } } return null; } catch (IOException e) { throw new DriveExceptionMappingService().map("Upload failed", e, file); } } @Override public long getContentLength() { return status.getLength(); } }; return this.write(file, status, command); }
From source file:org.opensaml.soap.client.soap11.encoder.http.impl.HttpClientRequestSOAP11Encoder.java
/** * Create the request entity that makes up the POST message body. * //from ww w . j ava 2 s . c o m * @param message message to be sent * @param charset character set used for the message * * @return request entity that makes up the POST message body * * @throws MessageEncodingException thrown if the message could not be marshalled */ protected HttpEntity createRequestEntity(@Nonnull final Envelope message, @Nullable final Charset charset) throws MessageEncodingException { try { final ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(); SerializeSupport.writeNode(XMLObjectSupport.marshall(message), arrayOut); return new ByteArrayEntity(arrayOut.toByteArray(), ContentType.create("text/xml", charset)); } catch (final MarshallingException e) { throw new MessageEncodingException("Unable to marshall SOAP envelope", e); } }
From source file:com.alibaba.dubbo.rpc.protocol.springmvc.support.ApacheHttpClient.java
private ContentType getContentType(Request request) { ContentType contentType = ContentType.DEFAULT_TEXT; for (Map.Entry<String, Collection<String>> entry : request.headers().entrySet()) if (entry.getKey().equalsIgnoreCase("Content-Type")) { Collection values = entry.getValue(); if (values != null && !values.isEmpty()) { String value = entry.getValue().iterator().next(); value = value.split(";")[0]; contentType = ContentType.create(value, request.charset()); break; }// ww w . jav a 2 s .co m } return contentType; }
From source file:org.n52.oxf.util.web.SimpleHttpClient.java
public HttpResponse executePost(String uri, String payloadToSend) throws HttpClientException { return executePost(uri, payloadToSend, ContentType.create("text/xml", Consts.UTF_8)); }
From source file:de.ii.xtraplatform.ogc.csw.client.CSWAdapter.java
private HttpResponse requestPOST(CSWOperation operation) throws ParserConfigurationException { URI url = findUrl(operation.getOperation(), CSW.METHOD.POST); HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient; URIBuilder uri = new URIBuilder(url); String xml = operation.toXml(nsStore, version); LOGGER.debug("{}\n{}", uri, xml); HttpPost httpPost;//from w w w.ja va 2 s . c o m HttpResponse response = null; try { httpPost = new HttpPost(uri.build()); for (String key : operation.getRequestHeaders().keySet()) { httpPost.setHeader(key, operation.getRequestHeaders().get(key)); } // TODO: temporary basic auth hack if (useBasicAuth) { String basic_auth = new String(Base64.encodeBase64((user + ":" + password).getBytes())); httpPost.addHeader("Authorization", "Basic " + basic_auth); } StringEntity xmlEntity = new StringEntity(xml, ContentType.create("text/plain", "UTF-8")); httpPost.setEntity(xmlEntity); response = httpClient.execute(httpPost, new BasicHttpContext()); // check http status checkResponseStatus(response.getStatusLine().getStatusCode(), uri); } catch (SocketTimeoutException ex) { if (ignoreTimeouts) { //LOGGER.warn(FrameworkMessages.POST_REQUEST_TIMED_OUT_AFTER_MS_URL_REQUEST, HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri.toString(), xml); } response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, ""); response.setEntity(new StringEntity("", ContentType.TEXT_XML)); } catch (IOException ex) { //LOGGER.error(ERROR_IN_POST_REQUEST_TO_URL_REQUEST, uri.toString(), xml, ex); //LOGGER.debug("Error requesting URL: {}", uri.toString()); try { if (!isDefaultUrl(uri.build(), CSW.METHOD.POST)) { //LOGGER.info(FrameworkMessages.REMOVING_URL, uri.toString()); this.urls.remove(operation.getOperation().toString()); //LOGGER.info(FrameworkMessages.RETRY_WITH_DEFAULT_URL, this.urls.get("default")); return requestPOST(operation); } } catch (URISyntaxException ex0) { } //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString()); throw new ReadError("Failed requesting URL: '{}'", uri); } catch (URISyntaxException ex) { //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString()); throw new ReadError("Failed requesting URL: '{}'", uri); } catch (ReadError ex) { //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString()); throw ex; } //LOGGER.debug(FrameworkMessages.WFS_REQUEST_SUBMITTED); return response; }
From source file:org.camunda.bpm.engine.rest.standalone.AbstractEmptyBodyFilterTest.java
@Test public void testBodyIsNullAndContentTypeHasISOCharset() throws IOException { evaluatePostRequest(null, ContentType.create(MediaType.APPLICATION_JSON, "iso-8859-1").toString(), 200, true);//from w ww .j av a 2 s . com }