List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:com.android.unit_tests.TestHttpService.java
/** * This test case executes a series of simple POST requests using * the 'expect: continue' handshake. //w w w. j a va 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(); } }
From source file:com.basho.riak.client.util.ClientHelper.java
/** * Perform and HTTP request and return the resulting response using the * internal HttpClient./* w w w. j av a 2 s . c om*/ * * @param bucket * Bucket of the object receiving the request. * @param key * Key of the object receiving the request or null if the request * is for a bucket. * @param httpMethod * The HTTP request to perform; must not be null. * @param meta * Extra HTTP headers to attach to the request. Query parameters * are ignored; they should have already been used to construct * <code>httpMethod</code> and query parameters. * @param streamResponse * If true, the connection will NOT be released. Use * HttpResponse.getHttpMethod().getResponseBodyAsStream() to get * the response stream; HttpResponse.getBody() will return null. * * @return The HTTP response returned by Riak from executing * <code>httpMethod</code>. * * @throws RiakIORuntimeException * If an error occurs during communication with the Riak server * (i.e. HttpClient threw an IOException) */ HttpResponse executeMethod(String bucket, String key, HttpRequestBase httpMethod, RequestMeta meta, boolean streamResponse) { if (meta != null) { Map<String, String> headers = meta.getHeaders(); for (String header : headers.keySet()) { httpMethod.addHeader(header, headers.get(header)); } Map<String, String> queryParams = meta.getQueryParamMap(); if (!queryParams.isEmpty()) { URI originalURI = httpMethod.getURI(); List<NameValuePair> currentQuery = URLEncodedUtils.parse(originalURI, CharsetUtils.UTF_8.name()); List<NameValuePair> newQuery = new LinkedList<NameValuePair>(currentQuery); for (Map.Entry<String, String> qp : queryParams.entrySet()) { newQuery.add(new BasicNameValuePair(qp.getKey(), qp.getValue())); } // For this, HC4.1 authors, I hate you URI newURI; try { newURI = URIUtils.createURI(originalURI.getScheme(), originalURI.getHost(), originalURI.getPort(), originalURI.getPath(), URLEncodedUtils.format(newQuery, "UTF-8"), null); } catch (URISyntaxException e) { throw new RiakIORuntimeException(e); } httpMethod.setURI(newURI); } } HttpEntity entity; try { org.apache.http.HttpResponse response = httpClient.execute(httpMethod); int status = 0; if (response.getStatusLine() != null) { status = response.getStatusLine().getStatusCode(); } Map<String, String> headers = ClientUtils.asHeaderMap(response.getAllHeaders()); byte[] body = null; InputStream stream = null; entity = response.getEntity(); if (streamResponse) { stream = entity.getContent(); } else { if (null != entity) { body = EntityUtils.toByteArray(entity); } } if (!streamResponse) { EntityUtils.consume(entity); } return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod); } catch (IOException e) { httpMethod.abort(); return toss(new RiakIORuntimeException(e)); } }
From source file:edu.ucsb.nceas.ezid.EZIDService.java
/** * Send an HTTP request to the EZID service with a request body (for POST and PUT requests). * @param requestType the type of the service as an integer * @param uri endpoint to be accessed in the request * @param requestBody the String body to be encoded into the body of the request * @return byte[] containing the response body *///from w ww. j av a 2s .com private byte[] sendRequest(int requestType, String uri, String requestBody) throws EZIDException { HttpUriRequest request = null; log.debug("Trying uri: " + uri); switch (requestType) { case GET: request = new HttpGet(uri); break; case PUT: request = new HttpPut(uri); if (requestBody != null && requestBody.length() > 0) { StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPut) request).setEntity(myEntity); } break; case POST: request = new HttpPost(uri); if (requestBody != null && requestBody.length() > 0) { StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPost) request).setEntity(myEntity); } break; case DELETE: request = new HttpDelete(uri); break; default: throw new EZIDException("Unrecognized HTTP method requested."); } request.addHeader("Accept", "text/plain"); ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; try { body = httpclient.execute(request, handler); } catch (ClientProtocolException e) { throw new EZIDException(e.getMessage()); } catch (IOException e) { throw new EZIDException(e.getMessage()); } return body; }
From source file:com.basho.riak.client.http.util.ClientHelper.java
/** * Perform and HTTP request and return the resulting response using the * internal HttpClient./*from www. j ava2s . c o m*/ * * @param bucket * Bucket of the object receiving the request. * @param key * Key of the object receiving the request or null if the request * is for a bucket. * @param httpMethod * The HTTP request to perform; must not be null. * @param meta * Extra HTTP headers to attach to the request. Query parameters * are ignored; they should have already been used to construct * <code>httpMethod</code> and query parameters. * @param streamResponse * If true, the connection will NOT be released. Use * HttpResponse.getHttpMethod().getResponseBodyAsStream() to get * the response stream; HttpResponse.getBody() will return null. * * @return The HTTP response returned by Riak from executing * <code>httpMethod</code>. * * @throws RiakIORuntimeException * If an error occurs during communication with the Riak server * (i.e. HttpClient threw an IOException) */ HttpResponse executeMethod(String bucket, String key, HttpRequestBase httpMethod, RequestMeta meta, boolean streamResponse) { if (meta != null) { Map<String, String> headers = meta.getHeaders(); for (String header : headers.keySet()) { httpMethod.addHeader(header, headers.get(header)); } Map<String, String> queryParams = meta.getQueryParamMap(); if (!queryParams.isEmpty()) { URI originalURI = httpMethod.getURI(); List<NameValuePair> currentQuery = URLEncodedUtils.parse(originalURI, CharsetUtils.UTF_8.name()); List<NameValuePair> newQuery = new LinkedList<NameValuePair>(currentQuery); for (Map.Entry<String, String> qp : queryParams.entrySet()) { newQuery.add(new BasicNameValuePair(qp.getKey(), qp.getValue())); } // For this, HC4.1 authors, I hate you URI newURI; try { newURI = new URIBuilder(originalURI).setQuery(URLEncodedUtils.format(newQuery, "UTF-8")) .build(); } catch (URISyntaxException e) { e.printStackTrace(); throw new RiakIORuntimeException(e); } httpMethod.setURI(newURI); } } HttpEntity entity = null; try { org.apache.http.HttpResponse response = httpClient.execute(httpMethod); int status = 0; if (response.getStatusLine() != null) { status = response.getStatusLine().getStatusCode(); } Map<String, String> headers = ClientUtils.asHeaderMap(response.getAllHeaders()); byte[] body = null; InputStream stream = null; entity = response.getEntity(); if (streamResponse) { stream = entity.getContent(); } else { if (null != entity) { body = EntityUtils.toByteArray(entity); } } key = extractKeyFromResponseIfItWasNotAlreadyProvided(key, response); return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod); } catch (IOException e) { httpMethod.abort(); return toss(new RiakIORuntimeException(e)); } finally { if (!streamResponse && entity != null) { try { EntityUtils.consume(entity); } catch (IOException e) { // NO-OP } } } }
From source file:cm.aptoide.pt.RemoteInSearch.java
private String downloadFile(int position) { Vector<DownloadNode> tmp_serv = new Vector<DownloadNode>(); String getserv = new String(); String md5hash = null;/*from w w w . j a v a2s. co m*/ String repo = null; try { tmp_serv = db.getPathHash(apk_lst.get(position).apkid); if (tmp_serv.size() > 0) { DownloadNode node = tmp_serv.get(0); getserv = node.repo + "/" + node.path; md5hash = node.md5h; repo = node.repo; } if (getserv.length() == 0) throw new TimeoutException(); Message msg = new Message(); msg.arg1 = 0; msg.obj = new String(getserv); download_handler.sendMessage(msg); /*BufferedInputStream getit = new BufferedInputStream(new URL(getserv).openStream()); String path = new String(APK_PATH+apk_lst.get(position).name+".apk"); FileOutputStream saveit = new FileOutputStream(path); BufferedOutputStream bout = new BufferedOutputStream(saveit,1024); byte data[] = new byte[1024]; int readed = getit.read(data,0,1024); while(readed != -1) { bout.write(data,0,readed); readed = getit.read(data,0,1024); } bout.close(); getit.close(); saveit.close();*/ String path = new String(APK_PATH + apk_lst.get(position).name + ".apk"); FileOutputStream saveit = new FileOutputStream(path); DefaultHttpClient mHttpClient = new DefaultHttpClient(); HttpGet mHttpGet = new HttpGet(getserv); String[] logins = null; logins = db.getLogin(repo); if (logins != null) { URL mUrl = new URL(getserv); mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()), new UsernamePasswordCredentials(logins[0], logins[1])); } HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet); if (mHttpResponse.getStatusLine().getStatusCode() == 401) { return null; } else { byte[] buffer = EntityUtils.toByteArray(mHttpResponse.getEntity()); saveit.write(buffer); } File f = new File(path); Md5Handler hash = new Md5Handler(); if (md5hash == null || md5hash.equalsIgnoreCase(hash.md5Calc(f))) { return path; } else { return null; } } catch (Exception e) { return null; } }
From source file:com.okta.sdk.impl.http.httpclient.HttpClientRequestExecutor.java
protected byte[] toBytes(HttpEntity entity) throws IOException { return EntityUtils.toByteArray(entity); }
From source file:biocode.fims.ezid.EzidService.java
/** * Send an HTTP request to the EZID service with a request body (for POST and PUT requests). * * @param requestType the type of the service as an integer * @param uri endpoint to be accessed in the request * @param requestBody the String body to be encoded into the body of the request * * @return byte[] containing the response body *///from w ww . j a v a 2s .co m private byte[] sendRequest(int requestType, String uri, String requestBody) throws EzidException { HttpUriRequest request = null; log.debug("Trying uri: " + uri); System.out.println("uri = " + uri); switch (requestType) { case GET: request = new HttpGet(uri); break; case PUT: request = new HttpPut(uri); if (requestBody != null && requestBody.length() > 0) { try { StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPut) request).setEntity(myEntity); } catch (UnsupportedEncodingException e) { throw new EzidException(e); } } break; case POST: request = new HttpPost(uri); if (requestBody != null && requestBody.length() > 0) { try { System.out.println("requestBody = " + requestBody); StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPost) request).setEntity(myEntity); } catch (UnsupportedEncodingException e) { throw new EzidException(e); } } break; case DELETE: request = new HttpDelete(uri); break; default: throw new EzidException("Unrecognized HTTP method requested."); } request.addHeader("Accept", "text/plain"); /* HACK -- re-authorize on the fly as this was getting dropped on SI server*/ /*String auth = this.username + ":" + this.password; String encodedAuth = org.apache.commons.codec.binary.Base64.encodeBase64String(auth.getBytes()); request.addHeader("Authorization", "Basic " + encodedAuth); */ ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; try { body = httpClient.execute(request, handler); } catch (ClientProtocolException e) { throw new EzidException(e); } catch (IOException e) { throw new EzidException(e); } return body; }
From source file:immf.ImodeNetClient.java
/** * ?//from ww w .j a v a 2 s .com * * @param mailId * @param attacheId * @return */ private AttachedFile getAttachedFile(AttachType type, int folderId, String mailId, String fileId, String fileName) throws IOException { log.debug("# ? " + type + "/" + mailId + "/" + fileId); StringBuilder query = new StringBuilder(); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); query.append("folder.id=" + Integer.toString(folderId)); query.append("&folder.mail.id=" + mailId); if (type == AttachType.Attach) { query.append("&folder.attach.id=" + fileId); } else { query.append("&folder.mail.img.id=" + fileId); } query.append("&cdflg=0"); HttpGet get = null; try { if (type == AttachType.Attach) { get = new HttpGet(AttachedFileUrl + "?" + query.toString()); } else { get = new HttpGet(InlineFileUrl + "?" + query.toString()); } addDumyHeader(get); HttpResponse res = this.executeHttp(get); AttachedFile file = new AttachedFile(); file.setFolderId(folderId); file.setMailId(mailId); file.setId(fileId); file.setFilename(fileName); HttpEntity entity = res.getEntity(); file.setContentType(entity.getContentType().getValue()); file.setData(EntityUtils.toByteArray(entity)); log.info("?? " + file.getFilename()); log.info("Content-type " + file.getContentType()); log.info(" " + file.getData().length); return file; } finally { get.abort(); } }
From source file:ezid.EZIDService.java
/** * Send an HTTP request to the EZID service with a request body (for POST and PUT requests). * * @param requestType the type of the service as an integer * @param uri endpoint to be accessed in the request * @param requestBody the String body to be encoded into the body of the request * * @return byte[] containing the response body *//*from w w w .j a v a 2s . c o m*/ private byte[] sendRequest(int requestType, String uri, String requestBody) throws EZIDException { HttpUriRequest request = null; log.debug("Trying uri: " + uri); System.out.println("uri = " + uri); switch (requestType) { case GET: request = new HttpGet(uri); break; case PUT: request = new HttpPut(uri); if (requestBody != null && requestBody.length() > 0) { try { StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPut) request).setEntity(myEntity); } catch (UnsupportedEncodingException e) { throw new EZIDException(e); } } break; case POST: request = new HttpPost(uri); if (requestBody != null && requestBody.length() > 0) { try { System.out.println("requestBody = " + requestBody); StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPost) request).setEntity(myEntity); } catch (UnsupportedEncodingException e) { throw new EZIDException(e); } } break; case DELETE: request = new HttpDelete(uri); break; default: throw new EZIDException("Unrecognized HTTP method requested."); } request.addHeader("Accept", "text/plain"); /* HACK -- re-authorize on the fly as this was getting dropped on SI server*/ /*String auth = this.username + ":" + this.password; String encodedAuth = org.apache.commons.codec.binary.Base64.encodeBase64String(auth.getBytes()); request.addHeader("Authorization", "Basic " + encodedAuth); */ ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; try { body = httpclient.execute(request, handler); } catch (ClientProtocolException e) { throw new EZIDException(e); } catch (IOException e) { throw new EZIDException(e); } return body; }