List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr, ContentType contentType)
From source file:org.docx4j.services.client.ConverterHttp.java
/** * Convert byte array fromFormat to toFormat, streaming result to OutputStream os. * // ww w.ja v a 2 s. com * fromFormat supported: DOC, DOCX * * toFormat supported: PDF * * @param bytesIn * @param fromFormat * @param toFormat * @param os * @throws IOException * @throws ConversionException */ public void convert(byte[] bytesIn, Format fromFormat, Format toFormat, OutputStream os) throws IOException, ConversionException { checkParameters(fromFormat, toFormat); CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = getUrlForFormat(toFormat); HttpEntity reqEntity = new ByteArrayEntity(bytesIn, map(fromFormat)); // messy that API is different to FileEntity httppost.setEntity(reqEntity); execute(httpclient, httppost, os); } finally { httpclient.close(); } }
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 w ww .ja va 2s .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:net.fischboeck.discogs.BaseOperations.java
<T> T doPutRequest(String url, Object body, Class<T> type) throws ClientException { log.debug("[doPutRequest] url={}", url); CloseableHttpResponse response = null; try {/*from w w w .j av a 2s . c o m*/ HttpPut request = new HttpPut(url); request.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(body), ContentType.APPLICATION_JSON)); response = doHttpRequest(request); HttpEntity entity = response.getEntity(); return mapper.readValue(entity.getContent(), type); } catch (JsonProcessingException jpe) { throw new ClientException(jpe.getMessage()); } catch (IOException ioe) { throw new ClientException(ioe.getMessage()); } catch (EntityNotFoundException enfe) { return null; } finally { closeSafe(response); } }
From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl.java
@Override public byte[] send(byte[] request) { HttpClientContext context = HttpClientContext.create(); context.setTargetHost(host);// w ww . ja va2 s. c o m context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); context.setAuthCache(authCache); ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM); // Create the client with the AuthSchemeRegistry and manager HttpPost post = new HttpPost(toURI(url)); post.setEntity(entity); try (CloseableHttpResponse response = client.execute(post, context)) { final int statusCode = response.getStatusLine().getStatusCode(); if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) { return EntityUtils.toByteArray(response.getEntity()); } throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode); } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.debug("Failed to execute HTTP request", e); throw new RuntimeException(e); } }
From source file:org.sentilo.platform.server.request.SentiloRequestHandler.java
private void prepareErrorResponse(final HttpResponse response, final int errorCode, final String errorMessage, final List<String> errorDetails) { final ErrorMessage message = new ErrorMessage(errorCode, errorMessage, errorDetails); try {//from w w w. j a va 2s .co m final ByteArrayOutputStream baos = errorParser.writeInternal(message); response.setStatusCode(errorCode); response.setEntity( new ByteArrayEntity(baos.toByteArray(), PlatformJsonMessageConverter.DEFAULT_CONTENT_TYPE)); response.setHeader(HttpHeader.CONTENT_TYPE.toString(), PlatformJsonMessageConverter.DEFAULT_CONTENT_TYPE.toString()); } catch (final JsonConverterException jce) { response.setStatusCode(errorCode); response.setEntity(new ByteArrayEntity(jce.getMessage().getBytes())); } }
From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java
@Override public final <RQ, RS> Will<Response<RS>> post(String resource, RQ rq, Class<RS> clazz) throws RestEndpointIOException { HttpPost post = new HttpPost(spliceUrl(resource)); Serializer serializer = getSupportedSerializer(rq); ByteArrayEntity httpEntity = new ByteArrayEntity(serializer.serialize(rq), ContentType.create(serializer.getMimeType())); post.setEntity(httpEntity);/*from w w w. j a v a2 s .c om*/ return executeInternal(post, new ClassConverterCallback<RS>(serializers, clazz)); }
From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java
public byte[] send(byte[] request) { while (true) { HttpClientContext context = HttpClientContext.create(); context.setTargetHost(host);/*from w w w . j av a2s .c o m*/ // Set the credentials if they were provided. if (null != this.credentials) { context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); context.setAuthCache(authCache); } ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM); // Create the client with the AuthSchemeRegistry and manager HttpPost post = new HttpPost(uri); post.setEntity(entity); try (CloseableHttpResponse response = execute(post, context)) { final int statusCode = response.getStatusLine().getStatusCode(); if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) { return EntityUtils.toByteArray(response.getEntity()); } else if (HttpURLConnection.HTTP_UNAVAILABLE == statusCode) { LOG.debug("Failed to connect to server (HTTP/503), retrying"); continue; } throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode); } catch (NoHttpResponseException e) { // This can happen when sitting behind a load balancer and a backend server dies LOG.debug("The server failed to issue an HTTP response, retrying"); continue; } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.debug("Failed to execute HTTP request", e); throw new RuntimeException(e); } } }
From source file:com.github.lindenb.jvarkit.tools.ensembl.VcfEnsemblVepRest.java
private Object generic_vep(List<VariantContext> contexts, boolean xml_answer) throws IOException { LOG.info("Running VEP " + contexts.size()); InputStream response = null;/*from www. j av a 2 s . c o m*/ javax.xml.transform.Source inputSource = null; HttpPost httpPost = null; try { if (this.lastMillisec != -1L && this.lastMillisec + 5000 < System.currentTimeMillis()) { try { Thread.sleep(1000); } catch (Exception err) { } } httpPost = new HttpPost(this.server + this.extension); StringBuilder queryb = new StringBuilder(); queryb.append("{ \"variants\" : ["); for (int i = 0; i < contexts.size(); ++i) { VariantContext ctx = contexts.get(i); if (i > 0) queryb.append(","); queryb.append("\"").append(createInputContext(ctx)).append("\""); } queryb.append("]"); for (String s : new String[] { "canonical", "ccds", "domains", "hgvs", "numbers", "protein", "xref_refseq" }) { queryb.append(",\"").append(s).append("\":1"); } queryb.append("}"); byte postBody[] = queryb.toString().getBytes(); httpPost.setHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType()); httpPost.setHeader("Accept", ContentType.TEXT_XML.getMimeType()); //httpPost.setHeader("Content-Length", Integer.toString(postBody.length)); httpPost.setEntity(new ByteArrayEntity(postBody, ContentType.APPLICATION_JSON)); final CloseableHttpResponse httpResponse = httpClient.execute(httpPost); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode != 200) { throw new RuntimeException("Response code was not 200. Detected response was " + responseCode); } //response = new TeeInputStream( httpConnection.getInputStream(),System.err,false); response = httpResponse.getEntity().getContent(); if (this.teeResponse) { stderr().println(queryb); response = new TeeInputStream(response, stderr(), false); } if (xml_answer) { return documentBuilder.parse(response); } else { inputSource = new StreamSource(response); return unmarshaller.unmarshal(inputSource, Opt.class).getValue(); } } catch (Exception e) { throw new IOException(e); } finally { CloserUtil.close(response); if (httpPost != null) httpPost.releaseConnection(); this.lastMillisec = System.currentTimeMillis(); } }
From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java
@Override public final <RQ, RS> Will<Response<RS>> post(String resource, RQ rq, Type type) throws RestEndpointIOException { HttpPost post = new HttpPost(spliceUrl(resource)); Serializer serializer = getSupportedSerializer(rq); ByteArrayEntity httpEntity = new ByteArrayEntity(serializer.serialize(rq), ContentType.create(serializer.getMimeType())); post.setEntity(httpEntity);//from w w w. j ava2s. co m return executeInternal(post, new TypeConverterCallback<RS>(serializers, type)); }
From source file:org.elasticsearch.client.CustomRestHighLevelClientTests.java
/** * Mocks the synchronous request execution like if it was executed by Elasticsearch. *//*w w w . j a v a2 s . co m*/ private Response mockPerformRequest(Request request) throws IOException { assertThat(request.getOptions().getHeaders(), hasSize(1)); Header httpHeader = request.getOptions().getHeaders().get(0); final Response mockResponse = mock(Response.class); when(mockResponse.getHost()).thenReturn(new HttpHost("localhost", 9200)); ProtocolVersion protocol = new ProtocolVersion("HTTP", 1, 1); when(mockResponse.getStatusLine()).thenReturn(new BasicStatusLine(protocol, 200, "OK")); MainResponse response = new MainResponse(httpHeader.getValue(), Version.CURRENT, ClusterName.DEFAULT, "_na", Build.CURRENT); BytesRef bytesRef = XContentHelper.toXContent(response, XContentType.JSON, false).toBytesRef(); when(mockResponse.getEntity()) .thenReturn(new ByteArrayEntity(bytesRef.bytes, ContentType.APPLICATION_JSON)); RequestLine requestLine = new BasicRequestLine(HttpGet.METHOD_NAME, ENDPOINT, protocol); when(mockResponse.getRequestLine()).thenReturn(requestLine); return mockResponse; }