List of usage examples for org.apache.http.entity ByteArrayEntity setContentType
public void setContentType(Header header)
From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java
public void connect() throws IOException { if (!connected) { final String userInfo = url.getUserInfo(); final boolean isAuthenticationRequestedWithUsername = username != null && !username.equals(""); // Create the HTTP client and HTTP context for the client (we expect this to be fairly lightweight) final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams); final HttpContext httpContext = new BasicHttpContext(); // Set cookie store, creating a new one if none was provided to us if (cookieStore == null) cookieStore = new BasicCookieStore(); httpClient.setCookieStore(cookieStore); // Set proxy and host authentication if (proxyAuthState != null) httpContext.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); if (userInfo != null || isAuthenticationRequestedWithUsername) { // Make authentication preemptive; interceptor is added first, as the Authentication header is added // by HttpClient's RequestTargetAuthentication which is itself an interceptor, so our interceptor // needs to run before RequestTargetAuthentication, otherwise RequestTargetAuthentication won't find // the appropriate AuthState/AuthScheme/Credentials in the HttpContext // Don't add the interceptor if we don't want preemptive authentication! if (!"false".equals(preemptiveAuthentication)) { httpClient.addRequestInterceptor(preemptiveAuthHttpRequestInterceptor, 0); }/*from w w w. jav a2s. c o m*/ CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); final AuthScope authScope = new AuthScope(url.getHost(), url.getPort()); final Credentials credentials; if (userInfo != null) { // Set username and optional password specified on URL final int separatorPosition = userInfo.indexOf(":"); String username = separatorPosition == -1 ? userInfo : userInfo.substring(0, separatorPosition); String password = separatorPosition == -1 ? "" : userInfo.substring(separatorPosition + 1); // If the username/password contain special character, those character will be encoded, since we // are getting this from a URL. Now do the decoding. username = URLDecoder.decode(username, "utf-8"); password = URLDecoder.decode(password, "utf-8"); credentials = new UsernamePasswordCredentials(username, password); } else { // Set username and password specified externally credentials = domain == null ? new UsernamePasswordCredentials(username, password == null ? "" : password) : new NTCredentials(username, password, url.getHost(), domain); } credentialsProvider.setCredentials(authScope, credentials); } // If method has not been set, use GET // This can happen e.g. when this connection handler is used from URLFactory if (method == null) setRequestMethod("GET"); // Set all headers, final boolean skipAuthorizationHeader = userInfo != null || username != null; for (final Map.Entry<String, String[]> currentEntry : requestProperties.entrySet()) { final String currentHeaderName = currentEntry.getKey(); final String[] currentHeaderValues = currentEntry.getValue(); for (final String currentHeaderValue : currentHeaderValues) { // Skip over Authorization header if user authentication specified if (skipAuthorizationHeader && currentHeaderName.toLowerCase() .equals(Connection.AUTHORIZATION_HEADER.toLowerCase())) continue; method.addHeader(currentHeaderName, currentHeaderValue); } } // Create request entity with body if (method instanceof HttpEntityEnclosingRequest) { // Use the body that was set directly, or the result of writing to the OutputStream final byte[] body = (requestBody != null) ? requestBody : (os != null) ? os.toByteArray() : null; if (body != null) { final Header contentTypeHeader = method.getFirstHeader("Content-Type"); // Header names are case-insensitive for comparison if (contentTypeHeader == null) throw new ProtocolException("Can't set request entity: Content-Type header is missing"); final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(body); byteArrayEntity.setContentType(contentTypeHeader); ((HttpEntityEnclosingRequest) method).setEntity(byteArrayEntity); } } // Make request httpResponse = httpClient.execute(method, httpContext); connected = true; } }
From source file:com.basho.riak.client.http.util.ClientHelper.java
/** * See/* w ww . ja v a 2 s.co m*/ * {@link RiakClient#setBucketSchema(String, com.basho.riak.client.http.RiakBucketInfo, RequestMeta)} */ public HttpResponse setBucketSchema(String bucket, JSONObject schema, RequestMeta meta) { if (schema == null) { schema = new JSONObject(); } if (meta == null) { meta = new RequestMeta(); } meta.setHeader(Constants.HDR_ACCEPT, Constants.CTYPE_JSON); HttpPut put = new HttpPut(ClientUtils.makeURI(config, bucket)); ByteArrayEntity entity = new ByteArrayEntity(utf8StringToBytes(schema.toString())); entity.setContentType(Constants.CTYPE_JSON_UTF8); put.setEntity(entity); return executeMethod(bucket, null, put, meta); }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java
public HttpResponse execute(HttpRequest request) throws IOException { URI uri = createURI(request); HttpRequestBase internalRequest;//from w w w .j a va 2s. c om if (request.method == HttpMethod.HEAD) { internalRequest = new HttpHead(uri); } else { HttpMethodWithEntity methodWithEntity = new HttpMethodWithEntity(uri, request.method.name()); if (request.hasBody()) { ByteArrayEntity entity = new ByteArrayEntity(request.body.getBytes(StandardCharsets.UTF_8)); String contentType = request.headers().get(HttpHeaders.CONTENT_TYPE); if (Strings.hasLength(contentType)) { entity.setContentType(contentType); } else { entity.setContentType(ContentType.TEXT_PLAIN.toString()); } methodWithEntity.setEntity(entity); } internalRequest = methodWithEntity; } internalRequest.setHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name()); // headers if (request.headers().isEmpty() == false) { for (Map.Entry<String, String> entry : request.headers.entrySet()) { internalRequest.setHeader(entry.getKey(), entry.getValue()); } } // BWC - hack for input requests made to elasticsearch that do not provide the right content-type header! if (request.hasBody() && internalRequest.containsHeader("Content-Type") == false) { XContentType xContentType = XContentFactory.xContentType(request.body()); if (xContentType != null) { internalRequest.setHeader("Content-Type", xContentType.mediaType()); } } RequestConfig.Builder config = RequestConfig.custom(); setProxy(config, request, settingsProxy); HttpClientContext localContext = HttpClientContext.create(); // auth if (request.auth() != null) { ApplicableHttpAuth applicableAuth = httpAuthRegistry.createApplicable(request.auth); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); applicableAuth.apply(credentialsProvider, new AuthScope(request.host, request.port)); localContext.setCredentialsProvider(credentialsProvider); // preemptive auth, no need to wait for a 401 first AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(request.host, request.port, request.scheme.scheme()), basicAuth); localContext.setAuthCache(authCache); } // timeouts if (request.connectionTimeout() != null) { config.setConnectTimeout(Math.toIntExact(request.connectionTimeout.millis())); } else { config.setConnectTimeout(Math.toIntExact(defaultConnectionTimeout.millis())); } if (request.readTimeout() != null) { config.setSocketTimeout(Math.toIntExact(request.readTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(request.readTimeout.millis())); } else { config.setSocketTimeout(Math.toIntExact(defaultReadTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(defaultReadTimeout.millis())); } internalRequest.setConfig(config.build()); try (CloseableHttpResponse response = SocketAccess .doPrivileged(() -> client.execute(internalRequest, localContext))) { // headers Header[] headers = response.getAllHeaders(); Map<String, String[]> responseHeaders = new HashMap<>(headers.length); for (Header header : headers) { if (responseHeaders.containsKey(header.getName())) { String[] old = responseHeaders.get(header.getName()); String[] values = new String[old.length + 1]; System.arraycopy(old, 0, values, 0, old.length); values[values.length - 1] = header.getValue(); responseHeaders.put(header.getName(), values); } else { responseHeaders.put(header.getName(), new String[] { header.getValue() }); } } final byte[] body; // not every response has a content, i.e. 204 if (response.getEntity() == null) { body = new byte[0]; } else { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { try (InputStream is = new SizeLimitInputStream(maxResponseSize, response.getEntity().getContent())) { Streams.copy(is, outputStream); } body = outputStream.toByteArray(); } } return new HttpResponse(response.getStatusLine().getStatusCode(), body, responseHeaders); } }
From source file:com.sap.cloudlabs.connectivity.proxy.ProxyServlet.java
/** * Returns the request that points to the backend service defined by the provided * <code>urlToService</code> URL. The headers of the origin request are copied to * the backend request, except of "host" and "content-length". * /* w w w .j a v a 2 s .c om*/ * @param request * original request to the Web application * @param urlToService * URL to the targeted backend service * @return initialized backend service request * @throws IOException */ private HttpRequestBase getBackendRequest(HttpServletRequest request, String urlToService) throws IOException { String method = request.getMethod(); LOGGER.debug("HTTP method: " + method); HttpRequestBase backendRequest = null; if (HttpPost.METHOD_NAME.equals(method)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(request.getInputStream(), out); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); entity.setContentType(request.getHeader("Content-Type")); HttpPost post = new HttpPost(urlToService); post.setEntity(entity); backendRequest = post; } else if (HttpGet.METHOD_NAME.equals(method)) { HttpGet get = new HttpGet(urlToService); backendRequest = get; } else if (HttpPut.METHOD_NAME.equals(method)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(request.getInputStream(), out); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); entity.setContentType(request.getHeader("Content-Type")); HttpPut put = new HttpPut(urlToService); put.setEntity(entity); backendRequest = put; } else if (HttpDelete.METHOD_NAME.equals(method)) { HttpDelete delete = new HttpDelete(urlToService); backendRequest = delete; } // copy headers from Web application request to backend request, while // filtering the blocked headers LOGGER.debug("backend request headers:"); Collection<String> blockedHeaders = mergeLists(securityHandler, Arrays.asList(BLOCKED_REQUEST_HEADERS)); Enumeration<String> setCookieHeaders = request.getHeaders("Cookie"); while (setCookieHeaders.hasMoreElements()) { String cookieHeader = setCookieHeaders.nextElement(); if (blockedHeaders.contains(cookieHeader.toLowerCase())) { String replacedCookie = removeJSessionID(cookieHeader); backendRequest.addHeader("Cookie", replacedCookie); } LOGGER.debug("Cookie header => " + cookieHeader); } for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) { String headerName = e.nextElement().toString(); if (!blockedHeaders.contains(headerName.toLowerCase())) { backendRequest.addHeader(headerName, request.getHeader(headerName)); LOGGER.debug(" => " + headerName + ": " + request.getHeader(headerName)); } else { LOGGER.debug(" => " + headerName + ": blocked request header"); } } return backendRequest; }
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);/*from w ww. j a va 2 s .co m*/ 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:android.webkit.cts.TestWebServer.java
/** * Create a string entity for the given content. *//*from w w w . j ava 2 s . c o m*/ private ByteArrayEntity createEntity(byte[] data) { ByteArrayEntity entity = new ByteArrayEntity(data); entity.setContentType("text/html"); return entity; }
From source file:net.vivekiyer.GAL.ActiveSyncManager.java
/** * @param uri The URI to send the POST message to * @param requestXML The XML to send in the message * @param includePolicyKey Should we include the policyKey in the header * @return The POST request that can be sent to the server * @throws Exception// ww w . j a va 2 s.c o m * * Creates a POST request that can be sent to the Exchange server. This method * sets all the necessary headers in the POST message that are required for * the Exchange server to respond appropriately */ private HttpPost createHttpPost(String uri, String requestXML, boolean includePolicyKey) throws Exception { // Set the common headers HttpPost httpPost = new HttpPost(uri); httpPost.setHeader("User-Agent", "Android"); httpPost.setHeader("Accept", "*/*"); httpPost.setHeader("Content-Type", "application/vnd.ms-sync.wbxml"); // If we are connecting to Exchange 2010 or above // Lets tell the Exchange server that we are a 12.1 client // This is so we don't have to support sending of additional // information in the provision method if (getActiveSyncVersionFloat() >= 14.0) httpPost.setHeader("MS-ASProtocolVersion", "12.1"); // Else set the version to the highest version returned by the // Exchange server else httpPost.setHeader("MS-ASProtocolVersion", getActiveSyncVersion()); //Log.d(TAG, mActiveSyncVersion); httpPost.setHeader("Accept-Language", "en-us"); httpPost.setHeader("Authorization", mAuthString); // Include policy key if required if (includePolicyKey) httpPost.setHeader("X-MS-PolicyKey", mPolicyKey); // Add the XML to the request if (requestXML != null) { //Log.d(TAG, requestXML); // Set the body // Convert the XML to WBXML ByteArrayInputStream xmlParseInputStream = new ByteArrayInputStream(requestXML.toString().getBytes()); java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream(); wbxml.convertXmlToWbxml(xmlParseInputStream, output); byte[] bytes = output.toByteArray(); ByteArrayEntity myEntity = new ByteArrayEntity(bytes); myEntity.setContentType("application/vnd.ms-sync.wbxml"); httpPost.setEntity(myEntity); } return httpPost; }