List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:org.fcrepo.camel.FcrepoClientAuthTest.java
@Test public void testAuthNoPassword() throws IOException, FcrepoOperationFailedException { final int status = 200; final URI uri = create(baseUrl); final ByteArrayEntity entity = new ByteArrayEntity(rdfXml.getBytes()); testClient = new FcrepoClient("user", null, null, true); setField(testClient, "httpclient", mockHttpclient); entity.setContentType(RDF_XML);/*from www .j a va 2 s. co m*/ doSetupMockRequest(RDF_XML, entity, status); final FcrepoResponse response = testClient.get(uri, RDF_XML, null); assertEquals(response.getUrl(), uri); assertEquals(response.getStatusCode(), status); assertEquals(response.getContentType(), RDF_XML); assertEquals(response.getLocation(), null); assertEquals(IOUtils.toString(response.getBody()), rdfXml); }
From source file:com.sulacosoft.bitcoindconnector4j.BitcoindApiHandler.java
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String jsonRequest = String.format( "{\"jsonrpc\": \"2.0\", \"method\": \"%s\", \"params\": [%s], \"id\": %s}", method.getName(), buildParamsString(args), id.getAndIncrement()); HttpPost httpPost = new HttpPost(uri); httpPost.setEntity(new ByteArrayEntity(jsonRequest.getBytes(CHARACTER_ENCODING))); CloseableHttpResponse response = httpClient.execute(targetHost, httpPost, context); try {//from w ww . j a va 2s.c o m checkHttpErrors(response.getStatusLine().getStatusCode()); String jsonResponse = IOUtils.toString(response.getEntity().getContent(), CHARACTER_ENCODING); JSONObject jsonObject = JSONObject.fromObject(jsonResponse); MorphDynaBean baseResponse = (MorphDynaBean) JSONObject.toBean(jsonObject); checkBitcoindErrors((MorphDynaBean) baseResponse.get("error")); return deserializeResult(method, baseResponse.get("result")); } finally { response.close(); } }
From source file:nl.nn.adapterframework.extensions.cmis.CmisHttpSender.java
@Override public HttpRequestBase getMethod(URIBuilder uri, String message, ParameterValueList pvl, Map<String, String> headersParamsMap, IPipeLineSession session) throws SenderException { HttpRequestBase method = null;/*from w ww .jav a2 s. c o m*/ try { if (getMethodType().equals("GET")) { method = new HttpGet(uri.build()); } else if (getMethodType().equals("POST")) { HttpPost httpPost = new HttpPost(uri.build()); // send data if (pvl.getParameterValue("writer") != null) { Output writer = (Output) pvl.getParameterValue("writer").getValue(); ByteArrayOutputStream out = new ByteArrayOutputStream(); Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION); if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) { httpPost.setHeader("Content-Encoding", "gzip"); writer.write(new GZIPOutputStream(out, 4096)); } else { writer.write(out); } HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray())); httpPost.setEntity(entity); out.close(); method = httpPost; } } else if (getMethodType().equals("PUT")) { HttpPut httpPut = new HttpPut(uri.build()); // send data if (pvl.getParameterValue("writer") != null) { Output writer = (Output) pvl.getParameterValue("writer").getValue(); ByteArrayOutputStream out = new ByteArrayOutputStream(); Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION); if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) { httpPut.setHeader("Content-Encoding", "gzip"); writer.write(new GZIPOutputStream(out, 4096)); } else { writer.write(out); } HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray())); httpPut.setEntity(entity); out.close(); method = httpPut; } } else if (getMethodType().equals("DELETE")) { method = new HttpDelete(uri.build()); } else { throw new MethodNotSupportedException("method [" + getMethodType() + "] not implemented"); } } catch (Exception e) { throw new SenderException(e); } for (Map.Entry<String, String> entry : headers.entrySet()) { log.debug("append header [" + entry.getKey() + "] with value [" + entry.getValue() + "]"); method.addHeader(entry.getKey(), entry.getValue()); } //Cmis creates it's own contentType depending on the method and bindingType method.setHeader("Content-Type", getContentType()); log.debug(getLogPrefix() + "HttpSender constructed " + getMethodType() + "-method [" + method.getURI() + "] query [" + method.getURI().getQuery() + "] "); return method; }
From source file:org.metaeffekt.dcc.agent.DccAgentEndpoint.java
private HttpPut createPutRequest(String command, String deploymentId, String packageId, String unitId, byte[] payload) { StringBuilder sb = new StringBuilder("/"); sb.append(deploymentId).append("/"); if (!"clean".equals(command)) { sb.append("packages").append("/").append(packageId).append("/"); sb.append("units").append("/").append(unitId != null ? unitId + "/" : ""); }/*from www . ja va 2 s . c o m*/ String paramsPart = sb.toString(); URIBuilder uriBuilder = getUriBuilder(); String path = String.format("/%s%s%s", PATH_ROOT, paramsPart, command); uriBuilder.setPath(path); URI uri; try { uri = uriBuilder.build(); } catch (URISyntaxException e) { throw new RuntimeException(e); } HttpPut put = new HttpPut(uri); if (payload != null && payload.length > 0) { put.setEntity(new ByteArrayEntity(payload)); } if (requestConfig != null) { put.setConfig(requestConfig); } return put; }
From source file:org.zalando.logbook.httpclient.Request.java
@Override public org.zalando.logbook.HttpRequest withBody() throws IOException { if (request instanceof HttpEntityEnclosingRequest) { final HttpEntityEnclosingRequest foo = (HttpEntityEnclosingRequest) request; final InputStream content = foo.getEntity().getContent(); this.body = ByteStreams.toByteArray(content); foo.setEntity(new ByteArrayEntity(body)); } else {/*from w ww . ja va 2 s.c om*/ this.body = new byte[0]; } return this; }
From source file:com.aliyun.android.oss.task.MultipartUploadCompleteTask.java
/** * HttpPost//ww w .j av a 2 s.c om * * @throws UnsupportedEncodingException */ protected HttpUriRequest generateHttpRequest() { String requestUri = this.getOSSEndPoint() + httpTool.generateCanonicalizedResource("/" + OSSHttpTool.encodeUri(objectKey)); HttpPost httpPost = new HttpPost(requestUri); // ?? byte[] data = generateHttpEntity().getBytes(); String resource = httpTool.generateCanonicalizedResource("/" + bucketName + "/" + objectKey); String dateStr = Helper.getGMTDate(); String authorization = OSSHttpTool.generateAuthorization(accessId, accessKey, httpMethod.toString(), "", "", dateStr, "", resource); httpPost.setHeader(AUTHORIZATION, authorization); httpPost.setHeader(DATE, dateStr); try { httpPost.setEntity(new ByteArrayEntity(data)); } catch (Exception e) { Log.e(this.getClass().getName(), e.getMessage()); } return httpPost; }
From source file:com.iflytek.android.framework.volley.toolbox.HttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *//*from w ww . j a v a2 s .c o 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()); VolleyLog.d("1:" + request.getBodyContentType()); 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; } case Method.HEAD: return new HttpHead(request.getUrl()); case Method.OPTIONS: return new HttpOptions(request.getUrl()); case Method.TRACE: return new HttpTrace(request.getUrl()); case Method.PATCH: { HttpPatch patchRequest = new HttpPatch(request.getUrl()); patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(patchRequest, request); return patchRequest; } default: throw new IllegalStateException("Unknown request method."); } }
From source file:com.zlk.bigdemo.android.volley.toolbox.HttpClientStack.java
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError { HttpEntity entity = request.getMultiBody(); if (entity == null) { byte[] body = request.getBody(); if (body != null) { entity = new ByteArrayEntity(body); }/* w w w . j a v a 2 s .com*/ } if (entity != null) { httpRequest.setEntity(entity); } }
From source file:com.android.mms.service.HttpUtils.java
/** * A helper method to send or retrieve data through HTTP protocol. * * @param url The URL used in a GET request. Null when the method is * HTTP_POST_METHOD.//from ww w . jav a2 s .c om * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD. * @param method HTTP_POST_METHOD or HTTP_GET_METHOD. * @param isProxySet If proxy is set * @param proxyHost The host of the proxy * @param proxyPort The port of the proxy * @param resolver The custom name resolver to use * @param useIpv6 If we should use IPv6 address when the HTTP client resolves the host name * @param mmsConfig The MmsConfig to use * @return A byte array which contains the response data. * If an HTTP error code is returned, an IOException will be thrown. * @throws com.android.mms.service.exception.MmsHttpException if HTTP request gets error response (>=400) */ public static byte[] httpConnection(Context context, String url, byte[] pdu, int method, boolean isProxySet, String proxyHost, int proxyPort, NameResolver resolver, boolean useIpv6, MmsConfig.Overridden mmsConfig) throws MmsHttpException { final String methodString = getMethodString(method); Log.v(TAG, "HttpUtils: request param list\n" + "url=" + url + "\n" + "method=" + methodString + "\n" + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost + "\n" + "proxyPort=" + proxyPort + "\n" + "size=" + (pdu != null ? pdu.length : 0)); NetworkAwareHttpClient client = null; try { // Make sure to use a proxy which supports CONNECT. URI hostUrl = new URI(url); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); client = createHttpClient(context, resolver, useIpv6, mmsConfig); HttpRequest req = null; switch (method) { case HTTP_POST_METHOD: ByteArrayEntity entity = new ByteArrayEntity(pdu); // Set request content type. entity.setContentType("application/vnd.wap.mms-message"); HttpPost post = new HttpPost(url); post.setEntity(entity); req = post; break; case HTTP_GET_METHOD: req = new HttpGet(url); break; } // Set route parameters for the request. HttpParams params = client.getParams(); if (isProxySet) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort)); } req.setParams(params); // Set necessary HTTP headers for MMS transmission. req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT); // UA Profile URL header String xWapProfileTagName = mmsConfig.getUaProfTagName(); String xWapProfileUrl = mmsConfig.getUaProfUrl(); if (xWapProfileUrl != null) { Log.v(TAG, "HttpUtils: xWapProfUrl=" + xWapProfileUrl); req.addHeader(xWapProfileTagName, xWapProfileUrl); } // Extra http parameters. Split by '|' to get a list of value pairs. // Separate each pair by the first occurrence of ':' to obtain a name and // value. Replace the occurrence of the string returned by // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside // the value. And replace the occurrence of the string returned by // MmsConfig.getHttpParamsNaiKey() with the users NAI(Network Access Identifier) // inside the value. String extraHttpParams = mmsConfig.getHttpParams(); if (!TextUtils.isEmpty(extraHttpParams)) { // Parse the parameter list String paramList[] = extraHttpParams.split("\\|"); for (String paramPair : paramList) { String splitPair[] = paramPair.split(":", 2); if (splitPair.length == 2) { final String name = splitPair[0].trim(); final String value = resolveMacro(context, splitPair[1].trim(), mmsConfig); if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) { req.addHeader(name, value); } } } } req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, getCurrentAcceptLanguage(Locale.getDefault())); final HttpResponse response = client.execute(target, req); final StatusLine status = response.getStatusLine(); final HttpEntity entity = response.getEntity(); Log.d(TAG, "HttpUtils: status=" + status + " size=" + (entity != null ? entity.getContentLength() : -1)); for (Header header : req.getAllHeaders()) { if (header != null) { Log.v(TAG, "HttpUtils: header " + header.getName() + "=" + header.getValue()); } } byte[] body = null; if (entity != null) { try { if (entity.getContentLength() > 0) { body = new byte[(int) entity.getContentLength()]; DataInputStream dis = new DataInputStream(entity.getContent()); try { dis.readFully(body); } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "HttpUtils: Error closing input stream: " + e.getMessage()); } } } if (entity.isChunked()) { Log.d(TAG, "HttpUtils: transfer encoding is chunked"); int bytesTobeRead = mmsConfig.getMaxMessageSize(); byte[] tempBody = new byte[bytesTobeRead]; DataInputStream dis = new DataInputStream(entity.getContent()); try { int bytesRead = 0; int offset = 0; boolean readError = false; do { try { bytesRead = dis.read(tempBody, offset, bytesTobeRead); } catch (IOException e) { readError = true; Log.e(TAG, "HttpUtils: error reading input stream", e); break; } if (bytesRead > 0) { bytesTobeRead -= bytesRead; offset += bytesRead; } } while (bytesRead >= 0 && bytesTobeRead > 0); if (bytesRead == -1 && offset > 0 && !readError) { // offset is same as total number of bytes read // bytesRead will be -1 if the data was read till the eof body = new byte[offset]; System.arraycopy(tempBody, 0, body, 0, offset); Log.d(TAG, "HttpUtils: Chunked response length " + offset); } else { Log.e(TAG, "HttpUtils: Response entity too large or empty"); } } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "HttpUtils: Error closing input stream", e); } } } } finally { if (entity != null) { entity.consumeContent(); } } } if (status.getStatusCode() != 200) { // HTTP 200 is success. StringBuilder sb = new StringBuilder(); if (body != null) { sb.append("response: text=").append(new String(body)).append('\n'); } for (Header header : req.getAllHeaders()) { if (header != null) { sb.append("req header: ").append(header.getName()).append('=').append(header.getValue()) .append('\n'); } } for (Header header : response.getAllHeaders()) { if (header != null) { sb.append("resp header: ").append(header.getName()).append('=').append(header.getValue()) .append('\n'); } } Log.e(TAG, "HttpUtils: error response -- \n" + "mStatusCode=" + status.getStatusCode() + "\n" + "reason=" + status.getReasonPhrase() + "\n" + "url=" + url + "\n" + "method=" + methodString + "\n" + "isProxySet=" + isProxySet + "\n" + "proxyHost=" + proxyHost + "\n" + "proxyPort=" + proxyPort + (sb != null ? "\n" + sb.toString() : "")); throw new MmsHttpException(status.getReasonPhrase()); } return body; } catch (IOException e) { Log.e(TAG, "HttpUtils: IO failure", e); throw new MmsHttpException(e); } catch (URISyntaxException e) { Log.e(TAG, "HttpUtils: invalid url " + url); throw new MmsHttpException("Invalid url " + url); } finally { if (client != null) { client.close(); } } }
From source file:edu.si.services.camel.fcrepo.FcrepoIntegrationTest.java
private static void ingest(String pid, Path payload) throws IOException { if (!checkObjectExist(pid)) { String ingestURI = FEDORA_URI + "/objects/" + pid + "?format=info:fedora/fedora-system:FOXML-1.1&ignoreMime=true"; logger.debug("INGEST URI = {}", ingestURI); HttpPost ingest = new HttpPost(ingestURI); ingest.setEntity(new ByteArrayEntity(Files.readAllBytes(payload))); ingest.setHeader("Content-type", MediaType.TEXT_XML); try (CloseableHttpResponse pidRes = httpClient.execute(ingest)) { assertEquals("Failed to ingest " + pid + "!", SC_CREATED, pidRes.getStatusLine().getStatusCode()); logger.info("Ingested test object {}", EntityUtils.toString(pidRes.getEntity())); }// ww w . j a v a 2s . c o m } }