Java Code Examples for org.apache.http.entity.ByteArrayEntity#setContentType()
The following examples show how to use
org.apache.http.entity.ByteArrayEntity#setContentType() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RemoteResponse.java From logbook with MIT License | 6 votes |
@Override public State buffer(final HttpResponse response) throws IOException { @Nullable final HttpEntity entity = response.getEntity(); if (entity == null) { return new Passing(); } else { final byte[] body = toByteArray(entity); final ByteArrayEntity copy = new ByteArrayEntity(body); copy.setChunked(entity.isChunked()); copy.setContentEncoding(entity.getContentEncoding()); copy.setContentType(entity.getContentType()); response.setEntity(copy); return new Buffering(body); } }
Example 2
Source File: HttpClientRequestExecutorTest.java From esigate with Apache License 2.0 | 6 votes |
private HttpResponse createMockGzippedResponse(String content) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(baos); byte[] uncompressedBytes = content.getBytes(); gzos.write(uncompressedBytes, 0, uncompressedBytes.length); gzos.close(); byte[] compressedBytes = baos.toByteArray(); ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes); httpEntity.setContentType("text/html; charset=ISO-8859-1"); httpEntity.setContentEncoding("gzip"); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("p", 1, 2), HttpStatus.SC_OK, "OK"); BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine); httpResponse.addHeader("Content-type", "text/html; charset=ISO-8859-1"); httpResponse.addHeader("Content-encoding", "gzip"); httpResponse.setEntity(httpEntity); return httpResponse; }
Example 3
Source File: GoHttpClientHttpInvokerRequestExecutor.java From gocd with Apache License 2.0 | 6 votes |
@Override protected RemoteInvocationResult doExecuteRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception { HttpPost postMethod = new HttpPost(config.getServiceUrl()); ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray()); entity.setContentType(getContentType()); postMethod.setEntity(entity); BasicHttpContext context = null; postMethod.setHeader("X-Agent-GUID", defaultAgentRegistry.uuid()); postMethod.setHeader("Authorization", defaultAgentRegistry.token()); try (CloseableHttpResponse response = goAgentServerHttpClient.execute(postMethod, context)) { validateResponse(response); try (InputStream responseBody = getResponseBody(response)) { return readRemoteInvocationResult(responseBody, config.getCodebaseUrl()); } } }
Example 4
Source File: HttpDownloadHandler.java From cetty with Apache License 2.0 | 5 votes |
private RequestBuilder addFormParams(RequestBuilder requestBuilder, Seed seed) { if (seed.getRequestBody() != null) { ByteArrayEntity entity = new ByteArrayEntity(seed.getRequestBody().getBody()); entity.setContentType(seed.getRequestBody().getContentType()); requestBuilder.setEntity(entity); } return requestBuilder; }
Example 5
Source File: SparkJobServerClientImpl.java From SparkJobServerClient with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ public boolean uploadSparkJobJar(InputStream jarData, String appName) throws SparkJobServerClientException { if (jarData == null || appName == null || appName.trim().length() == 0) { throw new SparkJobServerClientException("Invalid parameters."); } HttpPost postMethod = new HttpPost(jobServerUrl + "jars/" + appName); postMethod.setConfig(getRequestConfig()); setAuthorization(postMethod); final CloseableHttpClient httpClient = buildClient(); try { ByteArrayEntity entity = new ByteArrayEntity(IOUtils.toByteArray(jarData)); postMethod.setEntity(entity); entity.setContentType("application/java-archive"); HttpResponse response = httpClient.execute(postMethod); int statusCode = response.getStatusLine().getStatusCode(); getResponseContent(response.getEntity()); if (statusCode == HttpStatus.SC_OK) { return true; } } catch (Exception e) { logger.error("Error occurs when uploading spark job jars:", e); } finally { close(httpClient); closeStream(jarData); } return false; }
Example 6
Source File: DriverTest.java From esigate with Apache License 2.0 | 5 votes |
public void testGzipErrorPage() throws Exception { Properties properties = new Properties(); properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost"); HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); response.addHeader("Content-type", "Text/html;Charset=UTF-8"); response.addHeader("Content-encoding", "gzip"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(baos); byte[] uncompressedBytes = "é".getBytes("UTF-8"); gzos.write(uncompressedBytes, 0, uncompressedBytes.length); gzos.close(); byte[] compressedBytes = baos.toByteArray(); ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes); httpEntity.setContentType("Text/html;Charset=UTF-8"); httpEntity.setContentEncoding("gzip"); response.setEntity(httpEntity); mockConnectionManager.setResponse(response); Driver driver = createMockDriver(properties, mockConnectionManager); CloseableHttpResponse driverResponse; try { driverResponse = driver.proxy("/", request.build()); fail("We should get an HttpErrorPage"); } catch (HttpErrorPage e) { driverResponse = e.getHttpResponse(); } assertEquals("é", HttpResponseUtils.toString(driverResponse)); }
Example 7
Source File: HttpUriRequestConverter.java From webmagic with Apache License 2.0 | 5 votes |
private RequestBuilder addFormParams(RequestBuilder requestBuilder, Request request) { if (request.getRequestBody() != null) { ByteArrayEntity entity = new ByteArrayEntity(request.getRequestBody().getBody()); entity.setContentType(request.getRequestBody().getContentType()); requestBuilder.setEntity(entity); } return requestBuilder; }
Example 8
Source File: DapTestCommon.java From tds with BSD 3-Clause "New" or "Revised" License | 4 votes |
public HttpResponse execute(HttpRequestBase rq) throws IOException { URI uri = rq.getURI(); DapController controller = getController(uri); StandaloneMockMvcBuilder mvcbuilder = MockMvcBuilders.standaloneSetup(controller); mvcbuilder.setValidator(new TestServlet.NullValidator()); MockMvc mockMvc = mvcbuilder.build(); MockHttpServletRequestBuilder mockrb = MockMvcRequestBuilders.get(uri); // We need to use only the path part mockrb.servletPath(uri.getPath()); // Move any headers from rq to mockrb Header[] headers = rq.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header h = headers[i]; mockrb.header(h.getName(), h.getValue()); } // Since the url has the query parameters, // they will automatically be parsed and added // to the rb parameters. // Finally set the resource dir mockrb.requestAttr("RESOURCEDIR", this.resourcepath); // Now invoke the servlet MvcResult result; try { result = mockMvc.perform(mockrb).andReturn(); } catch (Exception e) { throw new IOException(e); } // Collect the output MockHttpServletResponse res = result.getResponse(); byte[] byteresult = res.getContentAsByteArray(); // Convert to HttpResponse HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, res.getStatus(), ""); if (response == null) throw new IOException("HTTPMethod.executeMock: Response was null"); Collection<String> keys = res.getHeaderNames(); // Move headers to the response for (String key : keys) { List<String> values = res.getHeaders(key); for (String v : values) { response.addHeader(key, v); } } ByteArrayEntity entity = new ByteArrayEntity(byteresult); String sct = res.getContentType(); entity.setContentType(sct); response.setEntity(entity); return response; }
Example 9
Source File: RemoteRepositoryManager.java From database with GNU General Public License v2.0 | 4 votes |
/** * * Create a new KB instance. * * @param namespace * The namespace of the KB instance. * @param properties * The configuration properties for that KB instance. * @param uuid * The {@link UUID} to be associated with this request. * * @throws Exception * * @see <a href="http://trac.bigdata.com/ticket/1257"> createRepository() * does not set the namespace on the Properties</a> */ public void createRepository(final String namespace, final Properties properties, final UUID uuid) throws Exception { if (namespace == null) throw new IllegalArgumentException(); if (properties == null) throw new IllegalArgumentException(); if (uuid == null) throw new IllegalArgumentException(); // if (properties.getProperty(OPTION_CREATE_KB_NAMESPACE) == null) // throw new IllegalArgumentException("Property not defined: " // + OPTION_CREATE_KB_NAMESPACE); // Set the namespace property. final Properties tmp = PropertyUtil.flatCopy(properties); tmp.setProperty(OPTION_CREATE_KB_NAMESPACE, namespace); /* * Note: This operation does not currently permit embedding into a * read/write tx. */ final ConnectOptions opts = newConnectOptions(baseServiceURL + "/namespace", uuid, null/* tx */); JettyResponseListener response = null; // Setup the request entity. { final PropertiesFormat format = PropertiesFormat.XML; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PropertiesWriter writer = PropertiesWriterRegistry.getInstance().get(format).getWriter(baos); writer.write(tmp); final byte[] data = baos.toByteArray(); final ByteArrayEntity entity = new ByteArrayEntity(data); entity.setContentType(format.getDefaultMIMEType()); opts.entity = entity; } try { checkResponseCode(response = doConnect(opts)); } finally { if (response != null) response.abort(); } }
Example 10
Source File: ApacheHTTPResponse.java From jbosh with Apache License 2.0 | 4 votes |
/** * Create and send a new request to the upstream connection manager, * providing deferred access to the results to be returned. * * @param client client instance to use when sending the request * @param cfg client configuration * @param params connection manager parameters from the session creation * response, or {@code null} if the session has not yet been established * @param request body of the client request */ ApacheHTTPResponse( final HttpClient client, final BOSHClientConfig cfg, final CMSessionParams params, final AbstractBody request) { super(); this.client = client; this.context = new BasicHttpContext(); this.post = new HttpPost(cfg.getURI().toString()); this.sent = false; try { String xml = request.toXML(); byte[] data = xml.getBytes(CHARSET); String encoding = null; if (cfg.isCompressionEnabled() && params != null) { AttrAccept accept = params.getAccept(); if (accept != null) { if (accept.isAccepted(ZLIBCodec.getID())) { encoding = ZLIBCodec.getID(); data = ZLIBCodec.encode(data); } else if (accept.isAccepted(GZIPCodec.getID())) { encoding = GZIPCodec.getID(); data = GZIPCodec.encode(data); } } } ByteArrayEntity entity = new ByteArrayEntity(data); entity.setContentType(CONTENT_TYPE); if (encoding != null) { entity.setContentEncoding(encoding); } post.setEntity(entity); if (cfg.isCompressionEnabled()) { post.setHeader(ACCEPT_ENCODING, ACCEPT_ENCODING_VAL); } for(Map.Entry<String, String> header: cfg.getHttpHeaders().entrySet()) { post.addHeader(new BasicHeader(header.getKey(), header.getValue())); } } catch (Exception e) { toThrow = new BOSHException("Could not generate request", e); } }
Example 11
Source File: HttpComponentsHttpInvokerRequestExecutor.java From spring-analysis-note with MIT License | 3 votes |
/** * Set the given serialized remote invocation as request body. * <p>The default implementation simply sets the serialized invocation as the * HttpPost's request body. This can be overridden, for example, to write a * specific encoding and to potentially set appropriate HTTP request headers. * @param config the HTTP invoker configuration that specifies the target service * @param httpPost the HttpPost to set the request body on * @param baos the ByteArrayOutputStream that contains the serialized * RemoteInvocation object * @throws java.io.IOException if thrown by I/O methods */ protected void setRequestBody( HttpInvokerClientConfiguration config, HttpPost httpPost, ByteArrayOutputStream baos) throws IOException { ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray()); entity.setContentType(getContentType()); httpPost.setEntity(entity); }
Example 12
Source File: HttpComponentsHttpInvokerRequestExecutor.java From java-technology-stack with MIT License | 3 votes |
/** * Set the given serialized remote invocation as request body. * <p>The default implementation simply sets the serialized invocation as the * HttpPost's request body. This can be overridden, for example, to write a * specific encoding and to potentially set appropriate HTTP request headers. * @param config the HTTP invoker configuration that specifies the target service * @param httpPost the HttpPost to set the request body on * @param baos the ByteArrayOutputStream that contains the serialized * RemoteInvocation object * @throws java.io.IOException if thrown by I/O methods */ protected void setRequestBody( HttpInvokerClientConfiguration config, HttpPost httpPost, ByteArrayOutputStream baos) throws IOException { ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray()); entity.setContentType(getContentType()); httpPost.setEntity(entity); }
Example 13
Source File: HttpComponentsHttpInvokerRequestExecutor.java From lams with GNU General Public License v2.0 | 3 votes |
/** * Set the given serialized remote invocation as request body. * <p>The default implementation simply sets the serialized invocation as the * HttpPost's request body. This can be overridden, for example, to write a * specific encoding and to potentially set appropriate HTTP request headers. * @param config the HTTP invoker configuration that specifies the target service * @param httpPost the HttpPost to set the request body on * @param baos the ByteArrayOutputStream that contains the serialized * RemoteInvocation object * @throws java.io.IOException if thrown by I/O methods */ protected void setRequestBody( HttpInvokerClientConfiguration config, HttpPost httpPost, ByteArrayOutputStream baos) throws IOException { ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray()); entity.setContentType(getContentType()); httpPost.setEntity(entity); }
Example 14
Source File: HttpComponentsHttpInvokerRequestExecutor.java From spring4-understanding with Apache License 2.0 | 3 votes |
/** * Set the given serialized remote invocation as request body. * <p>The default implementation simply sets the serialized invocation as the * HttpPost's request body. This can be overridden, for example, to write a * specific encoding and to potentially set appropriate HTTP request headers. * @param config the HTTP invoker configuration that specifies the target service * @param httpPost the HttpPost to set the request body on * @param baos the ByteArrayOutputStream that contains the serialized * RemoteInvocation object * @throws java.io.IOException if thrown by I/O methods */ protected void setRequestBody( HttpInvokerClientConfiguration config, HttpPost httpPost, ByteArrayOutputStream baos) throws IOException { ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray()); entity.setContentType(getContentType()); httpPost.setEntity(entity); }
Example 15
Source File: RemoteRepository.java From database with GNU General Public License v2.0 | 2 votes |
/** * Post a GraphML file to the blueprints layer of the remote bigdata instance. */ public long postGraphML(final String path) throws Exception { // TODO Allow client to specify UUID for postGraphML. See #1254. final UUID uuid = UUID.randomUUID(); final ConnectOptions opts = mgr.newConnectOptions(sparqlEndpointURL, uuid, tx); opts.addRequestParam("blueprints"); JettyResponseListener response = null; try { final File file = new File(path); if (!file.exists()) { throw new RuntimeException("cannot locate file: " + file.getAbsolutePath()); } final byte[] data = IOUtil.readBytes(file); final ByteArrayEntity entity = new ByteArrayEntity(data); entity.setContentType(ConnectOptions.MIME_GRAPH_ML); opts.entity = entity; opts.setAcceptHeader(ConnectOptions.MIME_APPLICATION_XML); checkResponseCode(response = doConnect(opts)); final MutationResult result = mutationResults(response); return result.mutationCount; } finally { if (response != null) response.abort(); } }
Example 16
Source File: RemoteRepositoryManager.java From database with GNU General Public License v2.0 | 2 votes |
/** * * Initiate the data loader for a namespace within the a NSS * * @param properties * The properties for the DataLoader Servlet * * @throws Exception * * @see BLZG-1713 */ public void doDataLoader(final Properties properties) throws Exception { if (properties == null) throw new IllegalArgumentException(); final Properties tmp = PropertyUtil.flatCopy(properties); /* * Note: This operation does not currently permit embedding into a * read/write tx. */ final ConnectOptions opts = newConnectOptions(baseServiceURL + "/dataloader", UUID.randomUUID(), null/* tx */); JettyResponseListener response = null; // Setup the request entity. { final PropertiesFormat format = PropertiesFormat.XML; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PropertiesWriter writer = PropertiesWriterRegistry.getInstance().get(format).getWriter(baos); writer.write(tmp); final byte[] data = baos.toByteArray(); final ByteArrayEntity entity = new ByteArrayEntity(data); entity.setContentType(format.getDefaultMIMEType()); opts.entity = entity; opts.method = "POST"; } try { checkResponseCode(response = doConnect(opts)); } finally { if (response != null) response.abort(); } }