List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:spring.test.web.HttpComponentsHttpInvokerRequestExecutor.java
/** * Set the given serialized remote invocation as request body. * <p>The default implementation simply sets the serialized invocation as the * HttpPost's request body. This can be overridden, for example, to write a * specific encoding and to potentially set appropriate HTTP request headers. * @param config the HTTP invoker configuration that specifies the target service * @param httpPost the HttpPost to set the request body on * @param baos the ByteArrayOutputStream that contains the serialized * RemoteInvocation object//from ww w . ja va2s .c om * @throws java.io.IOException if thrown by I/O methods */ protected void setRequestBody(HttpInvokerClientConfiguration config, HttpPost httpPost, ByteArrayOutputStream baos) throws IOException { ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray()); entity.setContentType(getContentType()); httpPost.setEntity(entity); }
From source file:ing.rbi.poc.ResolveConnection.java
private String Login() { //This uses the imported google JSON jar Gson gson = new Gson(); DefaultHttpClient client = new DefaultHttpClient(); //Add Session to the end String SessionURI = uri + "/session"; //Set the type to Post HttpPost request = new HttpPost(SessionURI); //Construct the information request.addHeader("Content-Type", "application/vnd.emc.captiva+json; charset=utf-8"); request.addHeader("Accept", "application/vnd.emc.captiva+json, application/json"); //Create the object and set the properties loginRequest loginRequest = new loginRequest(); loginRequest.culture = "en-GB"; loginRequest.username = user;//w ww . ja v a 2 s. c om loginRequest.password = password; //Get the DeviceID -- Not working properly yet.. String androidID = Settings.Secure.ANDROID_ID; loginRequest.deviceId = androidID; //Serialise the JSON String json = gson.toJson(loginRequest); //Now try and post it try { request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8"))); HttpResponse response = client.execute(request); String strResponse = EntityUtils.toString(response.getEntity(), "UTF8"); Gson gsonResponse = new Gson(); loginResponse LoginResponse = null; // TODO SEB prevent crash if server response not valid try { LoginResponse = gsonResponse.fromJson(strResponse, loginResponse.class); } catch (Exception e) { //System.out.println("XXXX"); Log.d("======> SEB", "Error reading return of REST call. Is your VPN up?"); } //Get the ticket back // should test if strResponse not empty first! if (LoginResponse != null) ticket = LoginResponse.ticket; else { ticket = "null"; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return ticket; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return ticket; } //Now get the ticket finally { } return ticket; }
From source file:org.apache.edgent.connectors.http.HttpStreams.java
/** * Make an HTTP PUT request with JsonObject. <br> * //from www. ja v a2 s . co m * Method specifically works with JsonObjects. For each JsonObject in the * stream, HTTP PUT request is executed on provided uri. Request body is * filled using HttpEntity provided by body function. As a result, Response * is added to the response TStream.<br> * * Sample usage:<br> * * <pre> * {@code * DirectProvider ep = new DirectProvider(); * Topology topology = ep.newTopology(); * final String url = "http://httpbin.org/put"; * * JsonObject body = new JsonObject(); * body.addProperty("foo", "abc"); * body.addProperty("bar", 42); * * TStream<JsonObject> stream = topology.collection(Arrays.asList(body)); * TStream<JsonObject> rc = HttpStreams.putJson(stream, * HttpClients::noAuthentication, t -> url, t -> t); * } * </pre> * * <br> * See HttpTest for example. <br> * * @param stream - JsonObject TStream. * @param clientCreator - CloseableHttpClient supplier preferably created using {@link HttpClients} * @param uri - URI function which returns URI string * @param body - Function that returns JsonObject which will be set as a body for the request. * @return TStream of JsonObject which contains responses of PUT requests * * @see HttpStreams#requestsWithBody(TStream, Supplier, Function, Function, Function, BiFunction) */ public static TStream<JsonObject> putJson(TStream<JsonObject> stream, Supplier<CloseableHttpClient> clientCreator, Function<JsonObject, String> uri, UnaryOperator<JsonObject> body) { return HttpStreams.<JsonObject, JsonObject>requestsWithBody(stream, clientCreator, t -> HttpPut.METHOD_NAME, uri, t -> new ByteArrayEntity(body.apply(t).toString().getBytes()), HttpResponders.json()); }
From source file:org.springframework.remoting.httpinvoker.HttpComponentsHttpInvokerRequestExecutor.java
/** * Set the given serialized remote invocation as request body. * <p>The default implementation simply sets the serialized invocation as the * HttpPost's request body. This can be overridden, for example, to write a * specific encoding and to potentially set appropriate HTTP request headers. * @param config the HTTP invoker configuration that specifies the target service * @param httpPost the HttpPost to set the request body on * @param baos the ByteArrayOutputStream that contains the serialized * RemoteInvocation object// ww w . ja v a 2 s.co m * @throws java.io.IOException if thrown by I/O methods */ protected void setRequestBody(HttpInvokerClientConfiguration config, HttpPost httpPost, ByteArrayOutputStream baos) throws IOException { ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray()); entity.setContentType(getContentType()); httpPost.setEntity(entity); }
From source file:com.github.wnameless.spring.bulkapi.test.BulkApiTest.java
@Test public void bulkRequestToComplexMapping() throws Exception { BulkRequest req = new BulkRequest(); BulkOperation op = new BulkOperation(); op.setUrl("/home2/AAA/ccc"); op.setMethod("PUT"); op.getHeaders().put("Authorization", "Basic " + Base64Utils.encodeToString("user:password".getBytes())); req.getOperations().add(op);//from w w w . ja v a2 s . c o m HttpEntity entity = new ByteArrayEntity(mapper.writeValueAsString(req).getBytes("UTF-8")); post.setEntity(entity); HttpResponse response = client.execute(post); assertTrue(200 == response.getStatusLine().getStatusCode()); }
From source file:libthrift091.transport.THttpClient.java
private void flushUsingHttpClient() throws TTransportException { if (null == this.client) { throw new TTransportException("Null HttpClient, aborting."); }/*from ww w . j av a2 s . c o m*/ // Extract request and reset buffer byte[] data = requestBuffer_.toByteArray(); requestBuffer_.reset(); HttpPost post = null; InputStream is = null; try { // Set request to path + query string post = new HttpPost(this.url_.getFile()); // // Headers are added to the HttpPost instance, not // to HttpClient. // post.setHeader("Content-Type", "application/x-thrift"); post.setHeader("Accept", "application/x-thrift"); post.setHeader("User-Agent", "Java/THttpClient/HC"); if (null != customHeaders_) { for (Map.Entry<String, String> header : customHeaders_.entrySet()) { post.setHeader(header.getKey(), header.getValue()); } } post.setEntity(new ByteArrayEntity(data)); HttpResponse response = this.client.execute(this.host, post); int responseCode = response.getStatusLine().getStatusCode(); // // Retrieve the inputstream BEFORE checking the status code so // resources get freed in the finally clause. // is = response.getEntity().getContent(); if (responseCode != HttpStatus.SC_OK) { throw new TTransportException("HTTP Response code: " + responseCode); } // Read the responses into a byte array so we can release the connection // early. This implies that the whole content will have to be read in // memory, and that momentarily we might use up twice the memory (while the // thrift struct is being read up the chain). // Proceeding differently might lead to exhaustion of connections and thus // to app failure. byte[] buf = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = 0; do { len = is.read(buf); if (len > 0) { baos.write(buf, 0, len); } } while (-1 != len); try { // Indicate we're done with the content. consume(response.getEntity()); } catch (IOException ioe) { // We ignore this exception, it might only mean the server has no // keep-alive capability. } inputStream_ = new ByteArrayInputStream(baos.toByteArray()); } catch (IOException ioe) { // Abort method so the connection gets released back to the connection manager if (null != post) { post.abort(); } throw new TTransportException(ioe); } finally { if (null != is) { // Close the entity's input stream, this will release the underlying connection try { is.close(); } catch (IOException ioe) { throw new TTransportException(ioe); } } } }
From source file:com.ctctlabs.ctctwsjavalib.CTCTConnection.java
/** * Perform a post request to the web service * @param link URL to perform the get request * @return status code returned by server *//*ww w . j ava 2 s.c om*/ InputStream doPostRequest(String link, String content) throws ClientProtocolException, IOException { HttpPost httppost = new HttpPost(link); httppost.addHeader("Content-Type", "application/atom+xml"); ByteArrayEntity entity = new ByteArrayEntity(content.getBytes()); httppost.setEntity(entity); if (accessToken != null) httppost.setHeader("Authorization", "Bearer " + accessToken); // for OAuth2.0 HttpResponse response = httpclient.execute(httppost); int status = response.getStatusLine().getStatusCode(); // If receive anything but a 201 status, return a null input stream if (status == HttpStatus.SC_CREATED) { return response.getEntity().getContent(); } else { return null; } }
From source file:org.opencastproject.remotetest.Main.java
private static void loadSeleneseData() throws Exception { System.out.println("Loading sample data for selenium HTML tests"); // get the zipped mediapackage from the classpath byte[] bytesToPost = IOUtils.toByteArray(Main.class.getResourceAsStream("/ingest.zip")); // post it to the ingest service HttpPost post = new HttpPost(BASE_URL + "/ingest/addZippedMediaPackage"); post.setEntity(new ByteArrayEntity(bytesToPost)); TrustedHttpClient client = getClient(); HttpResponse response = client.execute(post); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); String workflowXml = EntityUtils.toString(response.getEntity()); // Poll the workflow service to ensure this recording processes successfully String workflowId = WorkflowUtils.getWorkflowInstanceId(workflowXml); while (true) { if (WorkflowUtils.isWorkflowInState(workflowId, "SUCCEEDED")) { SELENESE_DATA_LOADED = true; break; }//from www. ja va 2s. com if (WorkflowUtils.isWorkflowInState(workflowId, "FAILED")) { Assert.fail("Unable to load sample data for selenese tests."); } Thread.sleep(5000); System.out.println("Waiting for sample data to process"); } returnClient(client); }
From source file:com.github.tomakehurst.wiremock.ProxyAcceptanceTest.java
@Test public void successfullyGetsResponseBinaryResponses() throws IOException { initWithDefaultConfig();/*from w ww . j a va2s . co m*/ final byte[] bytes = new byte[] { 0x10, 0x49, 0x6e, (byte) 0xb7, 0x46, (byte) 0xe6, 0x52, (byte) 0x95, (byte) 0x95, 0x42 }; HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext("/binary", new HttpHandler() { @Override public void handle(HttpExchange exchange) throws IOException { InputStream request = exchange.getRequestBody(); byte[] buffy = new byte[10]; request.read(buffy); if (Arrays.equals(buffy, bytes)) { exchange.sendResponseHeaders(200, bytes.length); OutputStream out = exchange.getResponseBody(); out.write(bytes); out.close(); } else { exchange.sendResponseHeaders(500, 0); exchange.close(); } } }); server.start(); proxyingServiceAdmin.register(post(urlEqualTo("/binary")).willReturn( aResponse().proxiedFrom("http://localhost:" + server.getAddress().getPort()).withBody(bytes))); WireMockResponse post = testClient.post("/binary", new ByteArrayEntity(bytes)); assertThat(post.statusCode(), is(200)); assertThat(post.binaryContent(), Matchers.equalTo(bytes)); }
From source file:net.lamp.support.HttpManager.java
/** * ???? formdata name="pic" name="file" ???????? * * @param url ?? * @param method "GET" or "POST" * @param params ?? * @param file ??????SdCard ? * // w w w .j a v a 2s . c o m * @return ? * @throws WeiboException ? */ public static String uploadFile(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); fileToUpload(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 WeiboHttpException(result, statusCode); } result = readHttpResponse(response); return result; } catch (IOException e) { throw new WeiboException(e); } }