List of usage examples for org.apache.http.entity ByteArrayEntity setContentType
public void setContentType(Header header)
From source file:org.apache.camel.component.http4.HttpProducer.java
/** * Creates a holder object for the data to send to the remote server. * * @param exchange the exchange with the IN message with data to send * @return the data holder//from ww w. j a v a2 s. c o m * @throws CamelExchangeException is thrown if error creating RequestEntity */ protected HttpEntity createRequestEntity(Exchange exchange) throws CamelExchangeException { Message in = exchange.getIn(); if (in.getBody() == null) { return null; } HttpEntity answer = in.getBody(HttpEntity.class); if (answer == null) { try { Object data = in.getBody(); if (data != null) { String contentType = ExchangeHelper.getContentType(exchange); if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) { // serialized java object Serializable obj = in.getMandatoryBody(Serializable.class); // write object to output stream ByteArrayOutputStream bos = new ByteArrayOutputStream(); HttpHelper.writeObjectToStream(bos, obj); ByteArrayEntity entity = new ByteArrayEntity(bos.toByteArray()); entity.setContentType(HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT); IOHelper.close(bos); answer = entity; } else if (data instanceof File || data instanceof GenericFile) { // file based (could potentially also be a FTP file etc) File file = in.getBody(File.class); if (file != null) { answer = new FileEntity(file, contentType); } } else if (data instanceof String) { // be a bit careful with String as any type can most likely be converted to String // so we only do an instanceof check and accept String if the body is really a String // do not fallback to use the default charset as it can influence the request // (for example application/x-www-form-urlencoded forms being sent) String charset = IOConverter.getCharsetName(exchange, false); StringEntity entity = new StringEntity((String) data, charset); entity.setContentType(contentType); answer = entity; } // fallback as input stream if (answer == null) { // force the body as an input stream since this is the fallback InputStream is = in.getMandatoryBody(InputStream.class); InputStreamEntity entity = new InputStreamEntity(is, -1); entity.setContentType(contentType); answer = entity; } } } catch (UnsupportedEncodingException e) { throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e); } catch (IOException e) { throw new CamelExchangeException("Error serializing message body", exchange, e); } } return answer; }
From source file:org.apache.sentry.tests.e2e.solr.AbstractSolrSentryTestBase.java
/** * Make a raw http request to specific cluster node. Node is of the format * host:port/context, i.e. "localhost:8983/solr" *///from w ww .j a v a2s .c o m protected String makeHttpRequest(CloudSolrServer server, String node, String httpMethod, String path, byte[] content, String contentType) throws Exception { HttpClient httpClient = server.getLbServer().getHttpClient(); URI uri = new URI("http://" + node + path); HttpRequestBase method = null; if ("GET".equals(httpMethod)) { method = new HttpGet(uri); } else if ("HEAD".equals(httpMethod)) { method = new HttpHead(uri); } else if ("POST".equals(httpMethod)) { method = new HttpPost(uri); } else if ("PUT".equals(httpMethod)) { method = new HttpPut(uri); } else { throw new IOException("Unsupported method: " + method); } if (method instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosing = (HttpEntityEnclosingRequestBase) method; ByteArrayEntity entityRequest = new ByteArrayEntity(content); entityRequest.setContentType(contentType); entityEnclosing.setEntity(entityRequest); } HttpEntity httpEntity = null; boolean success = false; String retValue = ""; try { final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); httpEntity = response.getEntity(); if (httpEntity != null) { InputStream is = httpEntity.getContent(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { IOUtils.copyLarge(is, os); os.flush(); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } retValue = os.toString(); } success = true; } finally { if (!success) { EntityUtils.consumeQuietly(httpEntity); method.abort(); } } return retValue; }
From source file:org.apache.sentry.tests.e2e.solr.AbstractSolrSentryTestCase.java
/** * Make a raw http request to specific cluster node. Node is of the format * host:port/context, i.e. "localhost:8983/solr" *///from w w w . j a va2s .c o m protected String makeHttpRequest(CloudSolrClient client, String node, String httpMethod, String path, byte[] content, String contentType, int expectedStatusCode) throws Exception { HttpClient httpClient = client.getLbClient().getHttpClient(); URI uri = new URI("http://" + node + path); HttpRequestBase method = null; if ("GET".equals(httpMethod)) { method = new HttpGet(uri); } else if ("HEAD".equals(httpMethod)) { method = new HttpHead(uri); } else if ("POST".equals(httpMethod)) { method = new HttpPost(uri); } else if ("PUT".equals(httpMethod)) { method = new HttpPut(uri); } else { throw new IOException("Unsupported method: " + method); } if (method instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosing = (HttpEntityEnclosingRequestBase) method; ByteArrayEntity entityRequest = new ByteArrayEntity(content); entityRequest.setContentType(contentType); entityEnclosing.setEntity(entityRequest); } HttpEntity httpEntity = null; boolean success = false; String retValue = ""; try { final HttpResponse response = httpClient.execute(method); httpEntity = response.getEntity(); assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode()); if (httpEntity != null) { InputStream is = httpEntity.getContent(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { IOUtils.copyLarge(is, os); os.flush(); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } retValue = os.toString(); } success = true; } finally { if (!success) { EntityUtils.consumeQuietly(httpEntity); method.abort(); } } return retValue; }
From source file:org.coronastreet.gpxconverter.StravaForm.java
public void upload() { //httpClient = new DefaultHttpClient(); httpClient = HttpClientBuilder.create().build(); localContext = new BasicHttpContext(); cookieStore = new BasicCookieStore(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (doLogin()) { //log("Ok....logged in..."); try {/* w w w .java 2s . c o m*/ // Have to fetch the form to get the CSRF Token HttpGet get = new HttpGet(uploadFormURL); HttpResponse formResponse = httpClient.execute(get, localContext); //log("Fetched the upload form...: " + formResponse.getStatusLine()); org.jsoup.nodes.Document doc = Jsoup.parse(EntityUtils.toString(formResponse.getEntity())); String csrftoken, csrfparam; Elements metalinksParam = doc.select("meta[name=csrf-param]"); if (!metalinksParam.isEmpty()) { csrfparam = metalinksParam.first().attr("content"); } else { csrfparam = null; log("Missing csrf-param?"); } Elements metalinksToken = doc.select("meta[name=csrf-token]"); if (!metalinksToken.isEmpty()) { csrftoken = metalinksToken.first().attr("content"); } else { csrftoken = null; log("Missing csrf-token?"); } HttpPost request = new HttpPost(uploadURL); request.setHeader("X-CSRF-Token", csrftoken); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("method", new StringBody("post")); entity.addPart("new_uploader", new StringBody("1")); entity.addPart(csrfparam, new StringBody(csrftoken)); entity.addPart("files[]", new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx")); // Need to do this bit because without it you can't disable chunked encoding, and Strava doesn't support chunked. ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); entity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(false); bArrEntity.setContentEncoding(entity.getContentEncoding()); bArrEntity.setContentType(entity.getContentType()); request.setEntity(bArrEntity); HttpResponse response = httpClient.execute(request, localContext); if (response.getStatusLine().getStatusCode() != 200) { log("Failed to Upload"); HttpEntity en = response.getEntity(); if (en != null) { String output = EntityUtils.toString(en); log(output); } } else { HttpEntity ent = response.getEntity(); if (ent != null) { String output = EntityUtils.toString(ent); //log(output); JSONObject userInfo = new JSONArray(output).getJSONObject(0); //log("Object: " + userInfo.toString()); if (userInfo.get("workflow").equals("Error")) { log("Upload Error: " + userInfo.get("error")); } else { log("Successful Uploaded. ID is " + userInfo.get("id")); } } } httpClient.close(); } catch (Exception ex) { log("Exception? " + ex.getMessage()); ex.printStackTrace(); // handle exception here } } else { log("Failed to upload!"); } }
From source file:org.energy_home.jemma.internal.ah.m2m.device.HttpEntityXmlConverter.java
public HttpEntity getEntity(Object object) throws JAXBException, UnsupportedEncodingException { ByteArrayOutputStream b = getConverter().getByteArrayOutputStream(object); if (log.isDebugEnabled()) log.debug("toEntity:\n" + getPrintableString(b.toString())); ByteArrayEntity entity = new ByteArrayEntity(b.toByteArray()); entity.setContentType(HTTP_ENTITY_CONTENT_TYPE); return entity; }
From source file:org.fcrepo.client.utils.HttpHelperTest.java
private FedoraResourceImpl testLoadPropertiesWithStatus(final int statusCode) throws Exception { final String triples = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">" + "<rdf:Description rdf:about=\"http://localhost:8080/rest/foo\">" + "<mixinTypes xmlns=\"http://fedora.info/definitions/v4/repository#\" " + "rdf:datatype=\"http://www.w3.org/2001/XMLSchema#string\">fedora:resource</mixinTypes>" + "</rdf:Description>" + "</rdf:RDF>"; final FedoraRepository mockRepo = mock(FedoraRepository.class); when(mockRepo.getRepositoryUrl()).thenReturn(repoURL); final FedoraResourceImpl origResource = new FedoraResourceImpl(mockRepo, helper, "/foo"); final HttpResponse mockResponse = mock(HttpResponse.class); final ByteArrayEntity entity = new ByteArrayEntity(triples.getBytes()); entity.setContentType("application/rdf+xml"); final Header etagHeader = new BasicHeader("Etag", etag); final Header[] etagHeaders = new Header[] { etagHeader }; final StatusLine mockStatus = mock(StatusLine.class); when(mockClient.execute(any(HttpGet.class), any(HttpContext.class))).thenReturn(mockResponse); when(mockResponse.getEntity()).thenReturn(entity); when(mockResponse.getHeaders("ETag")).thenReturn(etagHeaders); when(mockResponse.getStatusLine()).thenReturn(mockStatus); when(mockStatus.getStatusCode()).thenReturn(statusCode); return helper.loadProperties(origResource); }
From source file:org.opennms.netmgt.ncs.northbounder.NCSNorthbounder.java
private HttpEntity createEntity(List<NorthboundAlarm> alarms) { ByteArrayOutputStream out = null; OutputStreamWriter writer = null; try {/*ww w . j a v a 2 s . c om*/ out = new ByteArrayOutputStream(); writer = new OutputStreamWriter(out); // marshall the output JaxbUtils.marshal(toServiceAlarms(alarms), writer); // verify its matches the expected results byte[] utf8 = out.toByteArray(); ByteArrayEntity entity = new ByteArrayEntity(utf8); entity.setContentType("application/xml"); return entity; } catch (Exception e) { throw new NorthbounderException("failed to convert alarms to xml", e); } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(out); } }