List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:org.vuphone.vandyupon.test.EventMetaRequestTester.java
public static void main(String[] args) { HttpClient c = new DefaultHttpClient(); HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); String params = "type=eventmetarequest&id=2&resp=xml"; post.setEntity(new ByteArrayEntity(params.toString().getBytes())); try {/*from ww w .jav a 2s.co m*/ HttpResponse resp = c.execute(post); resp.getEntity().writeTo(System.out); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.vuphone.vandyupon.test.EventPostTester.java
public static void main(String[] args) { HttpClient c = new DefaultHttpClient(); HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); String params = "type=eventratingrequest&id=1&comments=true&numcom=10"; post.setEntity(new ByteArrayEntity(params.toString().getBytes())); try {// ww w . java2 s.c om HttpResponse resp = c.execute(post); resp.getEntity().writeTo(System.out); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.vuphone.vandyupon.test.EventRatingPostTest.java
public static void main(String[] args) { HttpClient c = new DefaultHttpClient(); HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); String params = "type=eventratingpost&event=1&user=chris&comment=awesome&value=1&resp=xml"; post.setEntity(new ByteArrayEntity(params.toString().getBytes())); try {//from w w w. jav a 2 s . c om HttpResponse resp = c.execute(post); resp.getEntity().writeTo(System.out); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.vuphone.vandyupon.test.EventRequestTester.java
public static void main(String[] args) { HttpClient c = new DefaultHttpClient(); HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); String params = "type=eventrequest&lat=36.1437&lon=-86.8046&dist=100&resp=xml&userid=chris"; post.setEntity(new ByteArrayEntity(params.toString().getBytes())); try {//from w w w .j a va2 s . c om HttpResponse resp = c.execute(post); resp.getEntity().writeTo(System.out); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.vuphone.vandyupon.test.EventRatingRequestTest.java
public static void main(String[] args) { HttpClient c = new DefaultHttpClient(); HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); String params = "type=eventpost&eventname=Test&starttime=" + System.currentTimeMillis() + "&endtime=" + (System.currentTimeMillis() + 6000000) + "&userid=chris&resp=xml&desc=a%20new%20event&locationlat=36.1437&locationlon=-86.8046"; post.setEntity(new ByteArrayEntity(params.toString().getBytes())); try {// w ww . j a v a2s .c o m HttpResponse resp = c.execute(post); resp.getEntity().writeTo(System.out); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.vuphone.vandyupon.test.ImagePostTester.java
public static void main(String[] args) { try {//from www . j a v a 2 s .c om File image = new File("2008-05-8 ChrisMikeNinaGrad.jpg"); byte[] bytes = new byte[(int) image.length()]; FileInputStream fis = new FileInputStream(image); int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = fis.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } fis.close(); HttpClient c = new DefaultHttpClient(); HttpPost post = new HttpPost( "http://afrl-gift.dre.vanderbilt.edu:8080/vandyupon/events/?type=eventimagepost&eventid=2" + "&time=" + System.currentTimeMillis() + "&resp=xml"); post.addHeader("Content-Type", "image/jpeg"); ByteArrayEntity bae = new ByteArrayEntity(bytes); post.setEntity(bae); try { HttpResponse resp = c.execute(post); resp.getEntity().writeTo(System.out); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.sourcecode.youku.ElementalHttpPost.java
public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {/*from ww w . j a v a2 s .c om*/ HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"), new ByteArrayEntity("This is the second test request".getBytes("UTF-8")), new InputStreamEntity(new ByteArrayInputStream( "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/servlets-examples/servlet/RequestInfoExample"); request.setEntity(requestBodies[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:org.eclipse.lyo.adapter.tdb.clients.OSLCTriplestoreAdapterResourceCreationClient.java
public static void main(String[] args) { String baseHTTPURI = "http://localhost:" + OSLC4JTDBApplication.portNumber + "/oslc4jtdb"; String projectId = "default"; // URI of the HTTP request String tdbResourceCreationFactoryURI = baseHTTPURI + "/services/" + projectId + "/resources"; // create RDF to add to the triplestore Model resourceRDFModel = ModelFactory.createDefaultModel(); Resource resource = ResourceFactory .createResource("http://localhost:8585/oslc4jtdb/services/default/resources/newBlock4"); Property property = ResourceFactory// w ww .ja v a 2 s .c o m .createProperty("http://localhost:8585/oslc4jtdb/services/default/resources/newProperty4"); RDFNode object = ResourceFactory .createResource("http://localhost:8585/oslc4jtdb/services/default/resources/newObject4"); resourceRDFModel.add(resource, property, object); StringWriter out = new StringWriter(); resourceRDFModel.write(out, "RDF/XML"); resourceRDFModel.write(System.out); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(tdbResourceCreationFactoryURI); String xml = out.toString(); HttpEntity entity; try { entity = new ByteArrayEntity(xml.getBytes("UTF-8")); post.setEntity(entity); post.setHeader("Accept", "application/rdf+xml"); HttpResponse response = client.execute(post); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:io.aos.protocol.http.httpcommon.ElementalHttpPost.java
public static void main(String... args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "Test/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {/*from w w w.ja v a 2s. co m*/ HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"), new ByteArrayEntity("This is the second test request".getBytes("UTF-8")), new InputStreamEntity(new ByteArrayInputStream( "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/servlets-examples/servlet/RequestInfoExample"); request.setEntity(requestBodies[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:com.weibo.wesync.client.NHttpClient2.java
public static void main(String[] args) throws Exception { RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem"); // //from w w w . j a v a 2 s . c om byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes()); password = RSAEncrypt.toHexString(cipher); // HTTP parameters for the client HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Use standard client-side protocol interceptors new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params); // Create client-side I/O reactor IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(1); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config); // Create HTTP connection pool BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(1); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); // Start the client thread t.start(); // Create HTTP requester // HttpAsyncRequester requester = new HttpAsyncRequester( // httpproc, new DefaultConnectionReuseStrategy(), params); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), new HttpHost("123.125.106.28", 8082, "http") }; final CountDownLatch latch = new CountDownLatch(targets.length); int callbackId = 0; for (int i = 0; i < 1; i++) { for (final HttpHost target : targets) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync"); // String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes()); // request.setHeader("authorization", "Basic " + usrpwd); request.setHeader("uid", "2565640713"); Meyou.MeyouPacket packet = null; if (callbackId == 0) { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.notice).build(); } else { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.wesync).build(); } ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray()); request.setEntity(entity); // BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html"); System.out.println("send ..."); HttpAsyncRequester requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, new BasicHttpContext(), // Handle HTTP response from a callback new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { StatusLine status = response.getStatusLine(); int code = status.getStatusCode(); if (code == 200) { try { latch.countDown(); DataInputStream in; in = new DataInputStream(response.getEntity().getContent()); int packetLength = in.readInt(); int start = 0; while (packetLength > 0) { ByteArrayOutputStream outstream = new ByteArrayOutputStream( packetLength); byte[] buffer = new byte[1024]; int len = 0; while (start < packetLength && (len = in.read(buffer, start, packetLength)) > 0) { outstream.write(buffer, 0, len); start += len; } Meyou.MeyouPacket packet0 = Meyou.MeyouPacket .parseFrom(outstream.toByteArray()); System.out.println(target + "->" + packet0); if ((len = in.read(buffer, start, 4)) > 0) { packetLength = Util.readPacketLength(buffer); } else { break; } } } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("error code=" + code + "|" + status.getReasonPhrase()); } } public void failed(final Exception ex) { latch.countDown(); System.out.println(target + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); Thread.sleep((long) (Math.random() * 10000)); } } // latch.await(); // System.out.println("Shutting down I/O reactor"); // ioReactor.shutdown(); // System.out.println("Done"); }