List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:ca.uhn.fhir.rest.client.apache.ApacheHttpClient.java
@Override public IHttpRequest createBinaryRequest(FhirContext theContext, IBaseBinary theBinary) { /*/* w w w . j a v a2 s. c o m*/ * Note: Be careful about changing which constructor we use for * ByteArrayEntity, as Android's version of HTTPClient doesn't support * the newer ones for whatever reason. */ ByteArrayEntity entity = new ByteArrayEntity(theBinary.getContent()); ApacheHttpRequest retVal = createHttpRequest(entity); addHeadersToRequest(retVal, null, theContext); retVal.addHeader(Constants.HEADER_CONTENT_TYPE, theBinary.getContentType()); return retVal; }
From source file:feign.httpclient.ApacheHttpClient.java
HttpUriRequest toHttpUriRequest(Request request, Request.Options options) throws UnsupportedEncodingException, MalformedURLException, URISyntaxException { RequestBuilder requestBuilder = RequestBuilder.create(request.method()); //per request timeouts RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(options.connectTimeoutMillis()) .setSocketTimeout(options.readTimeoutMillis()).build(); requestBuilder.setConfig(requestConfig); URI uri = new URIBuilder(request.url()).build(); requestBuilder.setUri(uri.getScheme() + "://" + uri.getAuthority() + uri.getRawPath()); //request query params List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, requestBuilder.getCharset().name()); for (NameValuePair queryParam : queryParams) { requestBuilder.addParameter(queryParam); }/*from w w w .j a v a 2s . c om*/ //request headers boolean hasAcceptHeader = false; for (Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) { String headerName = headerEntry.getKey(); if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) { hasAcceptHeader = true; } if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) { // The 'Content-Length' header is always set by the Apache client and it // doesn't like us to set it as well. continue; } for (String headerValue : headerEntry.getValue()) { requestBuilder.addHeader(headerName, headerValue); } } //some servers choke on the default accept string, so we'll set it to anything if (!hasAcceptHeader) { requestBuilder.addHeader(ACCEPT_HEADER_NAME, "*/*"); } //request body if (request.body() != null) { HttpEntity entity = null; if (request.charset() != null) { ContentType contentType = getContentType(request); String content = new String(request.body(), request.charset()); entity = new StringEntity(content, contentType); } else { entity = new ByteArrayEntity(request.body()); } requestBuilder.setEntity(entity); } return requestBuilder.build(); }
From source file:com.kixeye.relax.AsyncRestClient.java
/** * @see com.kixeye.relax.RestClient#post(java.lang.String, java.lang.String, java.lang.String, I, java.lang.Class, java.lang.Object) *//*from ww w . j a v a 2 s . co m*/ @Override public <I, O> HttpPromise<HttpResponse<O>> post(String path, String contentTypeHeader, String acceptHeader, I requestObject, final Class<O> responseType, Map<String, List<String>> additonalHeaders, Object... pathVariables) throws IOException { HttpPromise<HttpResponse<O>> promise = new HttpPromise<>(); HttpPost request = new HttpPost(UrlUtils.expand(uriPrefix + path, pathVariables)); if (requestObject != null) { request.setEntity(new ByteArrayEntity(serDe.serialize(contentTypeHeader, requestObject))); } if (contentTypeHeader != null) { request.setHeader("Content-Type", contentTypeHeader); } if (acceptHeader != null) { request.setHeader("Accept", acceptHeader); } if (additonalHeaders != null && !additonalHeaders.isEmpty()) { for (Entry<String, List<String>> header : additonalHeaders.entrySet()) { for (String value : header.getValue()) { request.addHeader(header.getKey(), value); } } } httpClient.execute(request, new AsyncRestClientResponseCallback<>(responseType, promise)); return promise; }
From source file:com.google.code.jerseyclients.httpclientfour.ApacheHttpClientFourHandler.java
public ClientResponse handle(final ClientRequest clientRequest) throws ClientHandlerException { if (this.jerseyHttpClientConfig.getApplicationCode() != null) { clientRequest.getHeaders().add(this.jerseyHttpClientConfig.getApplicationCodeHeader(), this.jerseyHttpClientConfig.getApplicationCode()); }/*from w ww.jav a2s.c om*/ if (this.jerseyHttpClientConfig.getOptionnalHeaders() != null) { for (Entry<String, String> entry : this.jerseyHttpClientConfig.getOptionnalHeaders().entrySet()) { clientRequest.getHeaders().add(entry.getKey(), entry.getValue()); } } // final Map<String, Object> props = cr.getProperties(); final HttpRequestBase method = getHttpMethod(clientRequest); // Set the read timeout final Integer readTimeout = jerseyHttpClientConfig.getReadTimeOut(); if (readTimeout != null) { HttpConnectionParams.setSoTimeout(method.getParams(), readTimeout.intValue()); } // FIXME penser au header http // DEBUG|wire.header|>> "Cache-Control: no-cache[\r][\n]" // DEBUG|wire.header|>> "Pragma: no-cache[\r][\n]" if (method instanceof HttpEntityEnclosingRequestBase) { final HttpEntityEnclosingRequestBase entMethod = (HttpEntityEnclosingRequestBase) method; if (clientRequest.getEntity() != null) { final RequestEntityWriter re = getRequestEntityWriter(clientRequest); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { re.writeRequestEntity(new CommittingOutputStream(baos) { @Override protected void commit() throws IOException { writeOutBoundHeaders(clientRequest.getHeaders(), method); } }); } catch (IOException ex) { throw new ClientHandlerException(ex); } final byte[] content = baos.toByteArray(); HttpEntity httpEntity = new ByteArrayEntity(content); entMethod.setEntity(httpEntity); } } else { writeOutBoundHeaders(clientRequest.getHeaders(), method); } try { StopWatch stopWatch = new StopWatch(); stopWatch.reset(); stopWatch.start(); HttpResponse httpResponse = client.execute(method); int httpReturnCode = httpResponse.getStatusLine().getStatusCode(); stopWatch.stop(); log.info("time to call rest url " + clientRequest.getURI() + ", " + stopWatch.getTime() + " ms"); if (httpReturnCode == Status.NO_CONTENT.getStatusCode()) { return new ClientResponse(httpReturnCode, getInBoundHeaders(httpResponse), IOUtils.toInputStream(""), getMessageBodyWorkers()); } return new ClientResponse(httpReturnCode, getInBoundHeaders(httpResponse), httpResponse.getEntity() == null ? IOUtils.toInputStream("") : httpResponse.getEntity().getContent(), getMessageBodyWorkers()); } catch (Exception e) { throw new ClientHandlerException(e); } }
From source file:com.easyhome.common.modules.network.HttpManager.java
/** * ? URL ?//from w w w. jav a 2s . c o m * * @param url ? * @param method "GET" or "POST" * @param params ? * @param file ????? SdCard ? * * @return ? * @throws com.sina.weibo.sdk.exception.WeiboException ? */ public static String openUrl(String url, String method, WeiboParameters params, String file) throws WeiboException { String result = ""; try { HttpClient client = getNewHttpClient(); HttpUriRequest request = null; ByteArrayOutputStream bos = null; client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN()); if (method.equals(HTTPMETHOD_GET)) { url = url + "?" + Utility.encodeUrl(params); HttpGet get = new HttpGet(url); request = get; } else if (method.equals(HTTPMETHOD_POST)) { HttpPost post = new HttpPost(url); request = post; byte[] data = null; String _contentType = params.getValue("content-type"); bos = new ByteArrayOutputStream(); if (!TextUtils.isEmpty(file)) { paramToUpload(bos, params); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); // ? // Utility.UploadImageUtils.revitionPostImageSize(file); imageContentToUpload(bos, file); } else { if (_contentType != null) { params.remove("content-type"); post.setHeader("Content-Type", _contentType); } else { post.setHeader("Content-Type", "application/x-www-form-urlencoded"); } String postParam = Utility.encodeParameters(params); data = postParam.getBytes("UTF-8"); bos.write(data); } data = bos.toByteArray(); bos.close(); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); } else if (method.equals("DELETE")) { request = new HttpDelete(url); } HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode != 200) { result = readHttpResponse(response); throw new WeiboException(result); } result = readHttpResponse(response); return result; } catch (IOException e) { throw new WeiboException(e); } }
From source file:org.flowable.mule.MuleSendActivityBehavior.java
public void execute(DelegateExecution execution) { String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution); String languageValue = this.getStringFromField(this.language, execution); String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution); String resultVariableValue = this.getStringFromField(this.resultVariable, execution); String usernameValue = this.getStringFromField(this.username, execution); String passwordValue = this.getStringFromField(this.password, execution); boolean isFlowable5Execution = false; Object payload = null;/*from w w w.j ava2 s. c om*/ if ((Context.getCommandContext() != null && Flowable5Util .isFlowable5ProcessDefinitionId(Context.getCommandContext(), execution.getProcessDefinitionId())) || (Context.getCommandContext() == null && Flowable5Util.getFlowable5CompatibilityHandler() != null)) { payload = Flowable5Util.getFlowable5CompatibilityHandler() .getScriptingEngineValue(payloadExpressionValue, languageValue, execution); isFlowable5Execution = true; } else { ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines(); payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution); } if (endpointUrlValue.startsWith("vm:")) { LocalMuleClient client = this.getMuleContext().getClient(); MuleMessage message = new DefaultMuleMessage(payload, this.getMuleContext()); MuleMessage resultMessage; try { resultMessage = client.send(endpointUrlValue, message); } catch (MuleException e) { throw new RuntimeException(e); } Object result = resultMessage.getPayload(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); } } else { HttpClientBuilder clientBuilder = HttpClientBuilder.create(); if (usernameValue != null && passwordValue != null) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(usernameValue, passwordValue); provider.setCredentials(new AuthScope("localhost", -1, "mule-realm"), credentials); clientBuilder.setDefaultCredentialsProvider(provider); } HttpClient client = clientBuilder.build(); HttpPost request = new HttpPost(endpointUrlValue); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(payload); oos.flush(); oos.close(); request.setEntity(new ByteArrayEntity(baos.toByteArray())); } catch (Exception e) { throw new FlowableException("Error setting message payload", e); } byte[] responseBytes = null; try { // execute the POST request HttpResponse response = client.execute(request); responseBytes = IOUtils.toByteArray(response.getEntity().getContent()); } catch (Exception e) { throw new RuntimeException(e); } finally { // release any connection resources used by the method request.releaseConnection(); } if (responseBytes != null) { try { ByteArrayInputStream in = new ByteArrayInputStream(responseBytes); ObjectInputStream is = new ObjectInputStream(in); Object result = is.readObject(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); } } catch (Exception e) { throw new FlowableException("Failed to read response value", e); } } } if (isFlowable5Execution) { Flowable5Util.getFlowable5CompatibilityHandler().leaveExecution(execution); } else { this.leave(execution); } }
From source file:com.subgraph.vega.internal.http.requests.RequestTask.java
private HttpEntity processGzipEncodedEntity(HttpResponse response, HttpEntity entity) throws IOException { final InputStream input = entity.getContent(); if (input == null) { response.setHeader(HTTP.CONTENT_LEN, "0"); return new ByteArrayEntity(new byte[0]); }//from ww w . java2 s .c o m final InputStream gzipInput = new GZIPInputStream(input); response.removeHeaders(HTTP.CONTENT_ENCODING); String contentType = (entity.getContentType() == null) ? (null) : (entity.getContentType().getValue()); RepeatableStreamingEntity newEntity = new RepeatableStreamingEntity(gzipInput, -1, true, entity.isChunked(), contentType, null); response.setHeader(HTTP.CONTENT_LEN, Long.toString(newEntity.getContentLength())); if (config.getMaximumResponseKilobytes() > 0) { newEntity.setMaximumInputKilobytes(config.getMaximumResponseKilobytes()); } return newEntity; }
From source file:es.eucm.eadventure.editor.plugin.vignette.ServerProxy.java
private boolean sendBytes(final byte[] bytes, String mime, String name) { boolean sent = false; try {/*from w w w. j a v a 2 s. c o m*/ HttpClient httpclient = getProxiedHttpClient(); String url = serviceURL + "/save.php?" + "m=" + getMac() + "&f=" + userPath + "&n=" + name; HttpPost post = new HttpPost(url); post.setEntity(new ByteArrayEntity(bytes)); post.setHeader("Content-Type", mime); HttpResponse response; response = httpclient.execute(post); if (response != null && Integer.toString(response.getStatusLine().getStatusCode()).startsWith("2")) { sent = true; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sent; }
From source file:com.android.volley.toolbox.ExtHttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. */// w w w. java 2 s. co m @SuppressWarnings("deprecation") /* protected */static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for backwards // compatibility. // If the request's post body is null, then the assumption is that // the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } default: throw new IllegalStateException("Unknown request method."); } }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java
public HttpResponse execute(HttpRequest request) throws IOException { URI uri = createURI(request); HttpRequestBase internalRequest;/* w ww.j ava 2 s .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); } }