List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:com.microsoft.services.sharepoint.http.FroyoHttpConnection.java
/** * Creates a request that can be accepted by the AndroidHttpClient * //from w w w . j a v a 2 s. c o m * @param request * The request information */ private static BasicHttpEntityEnclosingRequest createRealRequest(Request request) { BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(request.getVerb(), request.getUrl()); if (request.getContent() != null) { realRequest.setEntity(new ByteArrayEntity(request.getContent())); } Map<String, String> headers = request.getHeaders(); for (String key : headers.keySet()) { realRequest.addHeader(key, headers.get(key)); } return realRequest; }
From source file:kr.moonlightdriver.app.server.Restor.java
/** * Form? Entity? URL POST.//w w w. ja v a 2 s. co m * ?: ???. ? onComplete ? . * * @param url REST API? URL * @param json POST ? * @param callback / ? */ public static void Call(String url, String json, Callback callback) { try { new PostTask(url, callback).execute(new ByteArrayEntity(json.getBytes("UTF8"))); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:co.paralleluniverse.fibers.okhttp.apache.OkApacheClientTest.java
@Test public void postByteEntity() throws Exception { server.enqueue(new MockResponse()); final HttpPost post = new HttpPost(server.getUrl("/").toURI()); byte[] body = "Hello, world!".getBytes(UTF_8); post.setEntity(new ByteArrayEntity(body)); FiberOkHttpUtil.executeInFiber(client, post); RecordedRequest request = server.takeRequest(); assertEquals("Hello, world!", request.getBody().readUtf8()); assertEquals(request.getHeader("Content-Length"), "13"); }
From source file:com.nominanuda.web.http.BaseHttpTest.java
protected HttpResponse performEntityEnclosingMethod(String ct, byte[] body, HttpEntityEnclosingRequestBase post) throws IOException, ClientProtocolException { if (client == null) { client = buildClient(maxConnPerRoute); }/* ww w. j a va2 s . c om*/ ByteArrayEntity entity = new ByteArrayEntity(body); entity.setContentType(ct); post.setEntity(entity); return client.execute(post); }
From source file:com.github.horrorho.liquiddonkey.cloud.client.FileGroupsClient.java
public List<ICloud.MBSFileAuthToken> getFiles(HttpClient client, String dsPrsID, String mmeAuthToken, String mobileBackupUrl, String udid, String snapshot, Collection<ICloud.MBSFile> files) throws BadDataException, IOException { logger.trace("<< getFiles() < dsPrsID: {} udid: {} snapshot: {} files: {}", dsPrsID, udid, snapshot, files.size());/*from w w w .j a v a 2 s . c o m*/ logger.debug(marker, "-- getFiles() < files: {}", files); List<ICloud.MBSFile> postData = files.stream() .map(file -> ICloud.MBSFile.newBuilder().setFileID(file.getFileID()).build()) .collect(Collectors.toList()); byte[] encoded; try { encoded = ProtoBufArray.encode(postData); } catch (IOException ex) { throw new BadDataException(ex); } String uri = path(mobileBackupUrl, "mbs", dsPrsID, udid, snapshot, "getFiles"); HttpPost post = new HttpPost(uri); headers.mobileBackupHeaders(dsPrsID, mmeAuthToken).stream().forEach(post::addHeader); post.setEntity(new ByteArrayEntity(encoded)); List<ICloud.MBSFileAuthToken> tokens = client.execute(post, mbsFileAuthTokenListHandler); logger.debug(marker, "-- getFiles() > tokens: {}", tokens); logger.trace(">> getFiles() > {}", tokens.size()); return tokens; }
From source file:com.github.wnameless.spring.bulkapi.test.BulkApiTest.java
@Test public void testBatch() throws Exception { HttpEntity entity = new ByteArrayEntity(mapper.writeValueAsString(operationTimes(1000)).getBytes("UTF-8")); post.setEntity(entity);//from w w w.ja v a2 s . co m HttpResponse response = client.execute(post); String result = EntityUtils.toString(response.getEntity()); BulkResponse res = new Gson().getAdapter(new TypeToken<BulkResponse>() { }).fromJson(result); assertTrue(200 == Double.valueOf(res.getResults().get(0).getStatus())); assertEquals(1000, res.getResults().size()); }
From source file:com.microsoft.office365.http.FroyoHttpConnection.java
/** * Creates a request that can be accepted by the AndroidHttpClient * /*from w ww .j a v a 2s .c o m*/ * @param request * The request information * @throws UnsupportedEncodingException */ private static BasicHttpEntityEnclosingRequest createRealRequest(Request request) throws UnsupportedEncodingException { BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(request.getVerb(), request.getUrl()); if (request.getContent() != null) { realRequest.setEntity(new ByteArrayEntity(request.getContent())); } Map<String, String> headers = request.getHeaders(); for (String key : headers.keySet()) { realRequest.addHeader(key, headers.get(key)); } return realRequest; }
From source file:com.android.unit_tests.TestHttpService.java
/** * This test case executes a series of simple GET requests *//*from www . j a v a 2 s. c o m*/ @LargeTest public void testSimpleBasicHttpRequests() throws Exception { int reqNo = 20; Random rnd = new Random(); // Prepare some random data final 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 { String s = request.getRequestLine().getUri(); if (s.startsWith("/?")) { s = s.substring(2); } int index = Integer.parseInt(s); byte[] data = (byte[]) testData.get(index); ByteArrayEntity entity = new ByteArrayEntity(data); response.setEntity(entity); } }); this.server.start(); 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()); } BasicHttpRequest get = new BasicHttpRequest("GET", "/?" + r); HttpResponse response = this.client.execute(get, 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:edu.cmu.cylab.starslinger.transaction.WebEngine.java
private byte[] doPost(String uri, byte[] requestBody) throws ExchangeException { mCancelable = false;// ww w . ja v a 2 s.c o m if (!SafeSlinger.getApplication().isOnline()) { throw new ExchangeException(mCtx.getString(R.string.error_CorrectYourInternetConnection)); } // sets up parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); params.setBooleanParameter("http.protocol.expect-continue", false); if (mHttpClient == null) { mHttpClient = new CheckedHttpClient(params, mCtx); } HttpPost httppost = new HttpPost(uri); BasicResponseHandler responseHandler = new BasicResponseHandler(); byte[] reqData = null; HttpResponse response = null; long startTime = SystemClock.elapsedRealtime(); int statCode = 0; String statMsg = ""; String error = ""; try { // Execute HTTP Post Request httppost.addHeader("Content-Type", "application/octet-stream"); httppost.setEntity(new ByteArrayEntity(requestBody)); mTxTotalBytes = requestBody.length; final long totalTxBytes = TrafficStats.getTotalTxBytes(); final long totalRxBytes = TrafficStats.getTotalRxBytes(); if (totalTxBytes != TrafficStats.UNSUPPORTED) { mTxStartBytes = totalTxBytes; } if (totalRxBytes != TrafficStats.UNSUPPORTED) { mRxStartBytes = totalRxBytes; } response = mHttpClient.execute(httppost); reqData = responseHandler.handleResponse(response).getBytes("8859_1"); } catch (UnsupportedEncodingException e) { error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")"; } catch (HttpResponseException e) { // this subclass of java.io.IOException contains useful data for // users, do not swallow, handle properly statCode = e.getStatusCode(); statMsg = e.getLocalizedMessage(); error = (String.format(mCtx.getString(R.string.error_HttpCode), statCode) + ", \'" + statMsg + "\'"); } catch (java.io.IOException e) { // just show a simple Internet connection error, so as not to // confuse users error = mCtx.getString(R.string.error_CorrectYourInternetConnection); } catch (RuntimeException e) { error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")"; } catch (OutOfMemoryError e) { error = mCtx.getString(R.string.error_OutOfMemoryError); } finally { long msDelta = SystemClock.elapsedRealtime() - startTime; if (response != null) { StatusLine status = response.getStatusLine(); if (status != null) { statCode = status.getStatusCode(); statMsg = status.getReasonPhrase(); } } MyLog.d(TAG, uri + ", " + requestBody.length + "b sent, " + (reqData != null ? reqData.length : 0) + "b recv, " + statCode + " code, " + msDelta + "ms"); } if (!TextUtils.isEmpty(error) || reqData == null) { throw new ExchangeException(error); } return reqData; }
From source file:io.undertow.server.handlers.encoding.RequestContentEncodingTestCase.java
public void runTest(final String theMessage, String encoding) throws IOException { DefaultHttpClient client = new DefaultHttpClient(); try {/* ww w. j ava2s.c om*/ message = theMessage; HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/encode"); get.setHeader(Headers.ACCEPT_ENCODING_STRING, encoding); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING); Assert.assertEquals(encoding, header[0].getValue()); byte[] body = HttpClientUtils.readRawResponse(result); HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/decode"); post.setEntity(new ByteArrayEntity(body)); post.addHeader(Headers.CONTENT_ENCODING_STRING, encoding); result = client.execute(post); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); String sb = HttpClientUtils.readResponse(result); Assert.assertEquals(theMessage.length(), sb.length()); Assert.assertEquals(theMessage, sb); } finally { client.getConnectionManager().shutdown(); } }