List of usage examples for org.apache.http.entity ContentType create
private static ContentType create(HeaderElement headerElement)
From source file:httpasync.ZeroCopyHttpExchange.java
public static void main(final String[] args) throws Exception { CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); try {/*from ww w.j a v a2s.co m*/ httpclient.start(); File upload = new File(args[0]); File download = new File(args[1]); ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload, ContentType.create("text/plain")); ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) { @Override protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new ClientProtocolException("Upload failed: " + response.getStatusLine()); } return file; } }; Future<File> future = httpclient.execute(httpost, consumer, null); File result = future.get(); System.out.println("Response file length: " + result.length()); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }
From source file:com.boonya.http.async.examples.nio.client.ZeroCopyHttpExchange.java
public static void main(final String[] args) throws Exception { CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); try {//www . j av a 2 s. c o m httpclient.start(); File upload = new File(args[0]); File download = new File(args[1]); ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload, ContentType.create("text/plain")); ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) { @Override protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new ClientProtocolException("Upload failed: " + response.getStatusLine()); } return file; } }; Future<File> future = httpclient.execute(httpost, consumer, null); File result = future.get(); System.out.println("Response file length: " + result.length()); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); }
From source file:nayan.netty.client.FileUploadClient.java
private static void uploadFile() throws Exception { File file = new File("small.jpg"); HttpEntity httpEntity = MultipartEntityBuilder.create() .addBinaryBody("file", file, ContentType.create("image/jpeg"), file.getName()).build(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://localhost:8080"); httppost.setEntity(httpEntity);// w w w.j av a 2 s. c o m System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); response.close(); }
From source file:su.fmi.photoshareclient.remote.LoginHandler.java
public static boolean login(String username, char[] password) { try {/*ww w. j a va 2s . co m*/ ProjectProperties properties = new ProjectProperties(); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost( "http://" + properties.get("socket") + properties.get("restEndpoint") + "/user/login"); StringEntity input = new StringEntity( "{\"username\":\"" + username + "\",\"password\":\"" + new String(password) + "\"}", ContentType.create("application/json")); post.setHeader("Content-Type", "application/json"); post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(username, new String(password)), "UTF-8", false)); post.setEntity(input); if (username.isEmpty() || password.length == 0) { return false; } HttpResponse response = (HttpResponse) client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { String authString = username + ":" + new String(password); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); authStringEncr = new String(authEncBytes); return true; } else { return false; } } catch (UnsupportedEncodingException ex) { Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex); } return false; }
From source file:org.activiti.rest.content.service.api.HttpMultipartHelper.java
public static HttpEntity getMultiPartEntity(String fileName, String contentType, InputStream fileStream, Map<String, String> additionalFormFields) throws IOException { MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); if (additionalFormFields != null && !additionalFormFields.isEmpty()) { for (Entry<String, String> field : additionalFormFields.entrySet()) { entityBuilder.addTextBody(field.getKey(), field.getValue()); }//from w ww . j a va 2s .c om } entityBuilder.addBinaryBody(fileName, IOUtils.toByteArray(fileStream), ContentType.create(contentType), fileName); return entityBuilder.build(); }
From source file:com.yattatech.gcm.format.JsonFormat.java
@Override public HttpEntity getRequest(String registrationId, String message) throws Exception { final JSONObject json = new JSONObject(); final JSONObject data = new JSONObject(); json.element("registration_ids", new String[] { registrationId }); json.element("delay_while_idle", true); data.element("message", message); data.element("time", String.valueOf(System.currentTimeMillis())); data.element("agent", "GCMSenderTest"); json.element("data", data); return new StringEntity(json.toString(), ContentType.create("application/json")); }
From source file:com.joyent.manta.http.ContentTypeLookupTest.java
public void canFindDefault() { MantaHttpHeaders headers = new MantaHttpHeaders(EXAMPLE_HEADERS); ContentType troff = ContentType.create("application/x-troff"); ContentType jsonStream = ContentType.create("application/x-json-stream"); Assert.assertEquals(ContentTypeLookup.findOrDefaultContentType(null, troff).getMimeType(), troff.getMimeType());//from w w w . j a va2s.c o m Assert.assertEquals(ContentTypeLookup.findOrDefaultContentType(headers, troff).getMimeType(), troff.getMimeType()); headers.put("Content-Type", "application/x-json-stream; type=directory"); Assert.assertEquals(ContentTypeLookup.findOrDefaultContentType(headers, troff).getMimeType(), jsonStream.getMimeType()); }
From source file:org.apache.sling.testing.clients.util.InputStreamBodyWithLength.java
public InputStreamBodyWithLength(String resourcePath, String contentType, String fileName) throws ClientException { super(ResourceUtil.getResourceAsStream(resourcePath), ContentType.create(contentType), fileName); this.streamLength = getResourceStreamLength(resourcePath); }
From source file:org.rapidoid.http.HTTP.java
public static byte[] post(String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files) throws IOException, ClientProtocolException { headers = U.safe(headers);/* w w w . j a v a 2 s. c o m*/ data = U.safe(data); files = U.safe(files); CloseableHttpClient client = client(uri); try { HttpPost httppost = new HttpPost(uri); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, String> entry : files.entrySet()) { ContentType contentType = ContentType.create("application/octet-stream"); String filename = entry.getValue(); File file = IO.file(filename); builder = builder.addBinaryBody(entry.getKey(), file, contentType, filename); } for (Entry<String, String> entry : data.entrySet()) { ContentType contentType = ContentType.create("text/plain", "UTF-8"); builder = builder.addTextBody(entry.getKey(), entry.getValue(), contentType); } httppost.setEntity(builder.build()); for (Entry<String, String> e : headers.entrySet()) { httppost.addHeader(e.getKey(), e.getValue()); } Log.info("Starting HTTP POST request", "request", httppost.getRequestLine()); CloseableHttpResponse response = client.execute(httppost); try { int statusCode = response.getStatusLine().getStatusCode(); U.must(statusCode == 200, "Expected HTTP status code 200, but found: %s", statusCode); InputStream resp = response.getEntity().getContent(); return IOUtils.toByteArray(resp); } finally { response.close(); } } finally { client.close(); } }
From source file:com.google.mr4c.message.HttpMessageHandler.java
public void handleMessage(Message msg) throws IOException { HttpPost post = new HttpPost(m_uri); post.setEntity(new StringEntity(msg.getContent(), ContentType.create(msg.getContentType()))); s_log.info("POSTing message to [{}]: [{}]", m_uri, msg); HttpResponse response = m_client.execute(post); StatusLine statusLine = response.getStatusLine(); s_log.info("Status line: {}", statusLine); s_log.info("Content: {}", toString(response.getEntity())); if (statusLine.getStatusCode() >= 300) { throw new IOException(statusLine.toString()); }// ww w. ja va2 s .c om }