List of usage examples for org.apache.http.entity ByteArrayEntity setChunked
public void setChunked(boolean z)
From source file:com.google.apphosting.vmruntime.VmApiProxyDelegate.java
/** * Create an HTTP post request suitable for sending to the API server. * * @param environment The current VMApiProxyEnvironment * @param packageName The API call package * @param methodName The API call method * @param requestData The POST payload./* w w w . j a v a 2 s .c o m*/ * @param timeoutMs The timeout for this request * @return an HttpPost object to send to the API. */ // static HttpPost createRequest(VmApiProxyEnvironment environment, String packageName, String methodName, byte[] requestData, int timeoutMs) { // Wrap the payload in a RemoteApi Request. RemoteApiPb.Request remoteRequest = new RemoteApiPb.Request(); remoteRequest.setServiceName(packageName); remoteRequest.setMethod(methodName); remoteRequest.setRequestId(environment.getTicket()); remoteRequest.setRequestAsBytes(requestData); HttpPost request = new HttpPost("http://" + environment.getServer() + REQUEST_ENDPOINT); request.setHeader(RPC_STUB_ID_HEADER, REQUEST_STUB_ID); request.setHeader(RPC_METHOD_HEADER, REQUEST_STUB_METHOD); // Set TCP connection timeouts. HttpParams params = new BasicHttpParams(); params.setLongParameter(ConnManagerPNames.TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS); // Performance tweaks. params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, Boolean.TRUE); params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, Boolean.FALSE); request.setParams(params); // The request deadline can be overwritten by the environment, read deadline if available. Double deadline = (Double) (environment.getAttributes().get(API_DEADLINE_KEY)); if (deadline == null) { request.setHeader(RPC_DEADLINE_HEADER, Double.toString(TimeUnit.SECONDS.convert(timeoutMs, TimeUnit.MILLISECONDS))); } else { request.setHeader(RPC_DEADLINE_HEADER, Double.toString(deadline)); } // If the incoming request has a dapper trace header: set it on outgoing API calls // so they are tied to the original request. Object dapperHeader = environment.getAttributes() .get(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey); if (dapperHeader instanceof String) { request.setHeader(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.headerKey, (String) dapperHeader); } // If the incoming request has a Cloud trace header: set it on outgoing API calls // so they are tied to the original request. // TODO(user): For now, this uses the incoming span id - use the one from the active span. Object traceHeader = environment.getAttributes() .get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey); if (traceHeader instanceof String) { request.setHeader(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.headerKey, (String) traceHeader); } ByteArrayEntity postPayload = new ByteArrayEntity(remoteRequest.toByteArray(), ContentType.APPLICATION_OCTET_STREAM); postPayload.setChunked(false); request.setEntity(postPayload); return request; }
From source file:com.net.plus.common.http.transport.PostBytesHttpTransport.java
public byte[] send(HttpClient httpClient, Object obj) { byte[] bytes = (byte[]) obj; HttpPost post = new HttpPost(getSendUrl()); ByteArrayEntity entity = new ByteArrayEntity(bytes, ContentType.create(mimeType, charset)); entity.setChunked(true); post.setEntity(entity);//from w ww . j ava2 s . c o m try { byte[] response = httpClient.execute(post, resHandler); return response; } catch (ConnectException ce) { post.abort(); log.error("Http transport error." + getSendUrl().toString(), ce); /*CommunicationException cce = new CommunicationException("pe.connect_failed"); cce.setDefaultMessage(getSendUrl().toString()); throw cce;*/ } catch (Exception ex) { post.abort(); /*log.error("Http transport error."+getSendUrl().toString(), ex); throw new CommunicationException("pe.error.undefined", ex);*/ } return null; }
From source file:com.guardtime.ksi.service.client.http.apache.ApacheHttpClient.java
private ApacheHttpPostRequestFuture post(InputStream request, URL url) throws KSIClientException { try {/*from w w w. j ava2 s. co m*/ HttpPost httpRequest = new HttpPost(url.toURI()); httpRequest.setHeader(AbstractHttpClient.HEADER_NAME_CONTENT_TYPE, AbstractHttpClient.HEADER_APPLICATION_KSI_REQUEST); ByteArrayEntity entity = new ByteArrayEntity(Util.toByteArray(request)); entity.setChunked(false); httpRequest.setEntity(entity); Future<HttpResponse> future = this.apacheClient.execute(httpRequest, null); return new ApacheHttpPostRequestFuture(future); } catch (URISyntaxException e) { throw new KSIClientException("Invalid URI " + settings.getSigningUrl(), e); } catch (IOException e) { throw new KSIClientException("Reading data from stream failed", e); } }
From source file:com.intel.cosbench.client.swift.SwiftClient.java
public void storeObject(String container, String object, byte[] data) throws IOException, SwiftException { SwiftResponse response = null;/*w ww .j a v a 2 s . co m*/ try { method = HttpClientUtil.makeHttpPut(getObjectPath(container, object)); method.setHeader(X_AUTH_TOKEN, authToken); ByteArrayEntity entity = new ByteArrayEntity(data); entity.setChunked(false); entity.setContentType("application/octet-stream"); ((HttpPut) method).setEntity(entity); response = new SwiftResponse(client.execute(method)); if (response.getStatusCode() == SC_CREATED) return; if (response.getStatusCode() == SC_ACCEPTED) return; if (response.getStatusCode() == SC_NOT_FOUND) throw new SwiftFileNotFoundException("container not found: " + container, response.getResponseHeaders(), response.getStatusLine()); throw new SwiftException("unexpected return from server", response.getResponseHeaders(), response.getStatusLine()); } finally { if (response != null) response.consumeResposeBody(); } }
From source file:org.mule.module.http.functional.listener.HttpListenerAttachmentsTestCase.java
private HttpEntity createHttpEntity(boolean useChunkedMode) throws IOException { HttpEntity multipartEntity = getMultipartEntity(true); if (useChunkedMode) { //The only way to send multipart + chunked is putting the multipart content in an output stream entity. ByteArrayOutputStream multipartOutput = new ByteArrayOutputStream(); multipartEntity.writeTo(multipartOutput); multipartOutput.flush();/*w ww .j a v a 2 s . c o m*/ ByteArrayEntity byteArrayEntity = new ByteArrayEntity(multipartOutput.toByteArray()); multipartOutput.close(); byteArrayEntity.setChunked(true); byteArrayEntity.setContentEncoding(multipartEntity.getContentEncoding()); byteArrayEntity.setContentType(multipartEntity.getContentType()); return byteArrayEntity; } else { return multipartEntity; } }
From source file:majordodo.client.http.HTTPClientConnection.java
private Map<String, Object> post(String contentType, byte[] content) throws IOException { HttpPost httpget = new HttpPost(getBaseUrl()); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(configuration.getSotimeout()) .setConnectTimeout(configuration.getConnectionTimeout()).build(); httpget.setConfig(requestConfig);// www . jav a2 s . com ByteArrayEntity body = new ByteArrayEntity(content); body.setChunked(true); body.setContentType(contentType); httpget.setEntity(body); try (CloseableHttpResponse response1 = httpclient.execute(httpget, getContext());) { if (response1.getStatusLine().getStatusCode() != 200) { brokerFailed(); throw new IOException("HTTP request failed: " + response1.getStatusLine()); } return MAPPER.readValue(response1.getEntity().getContent(), Map.class); } }
From source file:com.android.unit_tests.TestHttpService.java
/** * This test case executes a series of simple POST requests with content length * delimited content. /*from www .ja v a 2s .co m*/ */ @LargeTest public void testSimpleHttpPostsWithContentLength() throws Exception { int reqNo = 20; Random rnd = new Random(); // Prepare some random data List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
From source file:com.android.unit_tests.TestHttpService.java
/** * This test case executes a series of simple POST requests with chunk * coded content content. /*w w w .ja v a2 s . c o m*/ */ @LargeTest public void testSimpleHttpPostsChunked() throws Exception { int reqNo = 20; Random rnd = new Random(); // Prepare some random data List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(20000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
From source file:com.android.unit_tests.TestHttpService.java
/** * This test case executes a series of simple HTTP/1.0 POST requests. *//*w ww.j a v a 2s. c o m*/ @LargeTest public void testSimpleHttpPostsHTTP10() throws Exception { int reqNo = 20; Random rnd = new Random(); // Prepare some random data List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); // Set protocol level to HTTP/1.0 this.client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); assertEquals(HttpVersion.HTTP_1_0, response.getStatusLine().getProtocolVersion()); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
From source file:com.android.unit_tests.TestHttpService.java
/** * This test case executes a series of simple POST requests using * the 'expect: continue' handshake. /*from www . j ava 2 s . c o m*/ */ @LargeTest public void testHttpPostsWithExpectContinue() throws Exception { int reqNo = 20; Random rnd = new Random(); // Prepare some random data List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); // Activate 'expect: continue' handshake this.client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }