List of usage examples for org.apache.http.entity FileEntity FileEntity
public FileEntity(File file, ContentType contentType)
From source file:com.bt.download.android.core.HttpFetcher.java
public void post(File file) throws IOException { HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort()); HttpPost httpPost = new HttpPost(uri); FileEntity fileEntity = new FileEntity(file, "binary/octet-stream"); fileEntity.setChunked(true);//from w w w . j av a 2s . com httpPost.setEntity(fileEntity); HttpParams params = httpPost.getParams(); HttpConnectionParams.setConnectionTimeout(params, timeout); HttpConnectionParams.setSoTimeout(params, timeout); HttpConnectionParams.setStaleCheckingEnabled(params, true); HttpConnectionParams.setTcpNoDelay(params, true); HttpClientParams.setRedirecting(params, true); HttpProtocolParams.setUseExpectContinue(params, false); HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT); try { HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost); if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() >= 300) throw new IOException("bad status code, upload file " + response.getStatusLine().getStatusCode()); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("Http error: " + e.getMessage()); } finally { // } }
From source file:com.uploader.Vimeo.java
private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file) throws IOException { // try(CloseableHttpClient client = HttpClientBuilder.create().build()) { CloseableHttpClient client = HttpClientBuilder.create().build(); // CloseableHttpClient client = HttpClients.createDefault(); System.out.println("Building HTTP Client"); // try {// ww w .j av a 2s . c om // client = // } catch(Exception e) { // System.out.println("Err in CloseableHttpClient"); // } // System.out.println(client); HttpRequestBase request = null; String url = null; if (endpoint.startsWith("http")) { url = endpoint; } else { url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString(); } System.out.println(url); if (methodName.equals(HttpGet.METHOD_NAME)) { request = new HttpGet(url); } else if (methodName.equals(HttpPost.METHOD_NAME)) { request = new HttpPost(url); } else if (methodName.equals(HttpPut.METHOD_NAME)) { request = new HttpPut(url); } else if (methodName.equals(HttpDelete.METHOD_NAME)) { request = new HttpDelete(url); } else if (methodName.equals(HttpPatch.METHOD_NAME)) { request = new HttpPatch(url); } request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2"); request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString()); HttpEntity entity = null; if (params != null) { ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { postParameters.add(new BasicNameValuePair(key, params.get(key))); } entity = new UrlEncodedFormEntity(postParameters); } else { if (file != null) { entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA); } } if (entity != null) { if (request instanceof HttpPost) { ((HttpPost) request).setEntity(entity); } else if (request instanceof HttpPatch) { ((HttpPatch) request).setEntity(entity); } else if (request instanceof HttpPut) { ((HttpPut) request).setEntity(entity); } } CloseableHttpResponse response = client.execute(request); String responseAsString = null; int statusCode = response.getStatusLine().getStatusCode(); if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) { JSONObject out = new JSONObject(); for (Header header : response.getAllHeaders()) { try { out.put(header.getName(), header.getValue()); } catch (Exception e) { System.out.println("Err in out.put"); } } responseAsString = out.toString(); } else if (statusCode != 204) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); responseAsString = out.toString("UTF-8"); out.close(); } JSONObject json = null; try { json = new JSONObject(responseAsString); } catch (Exception e) { json = new JSONObject(); } VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode); response.close(); client.close(); return vimeoResponse; // } catch(IOException e) { // System.out.println("Error Building HTTP Client"); // } }
From source file:org.xwiki.android.rest.HttpConnector.java
/** * Perform HTTP Put method with the raw data file * //from w w w . j av a2s . co m * @param Uri URL of XWiki RESTful API * @param filePath path of the file name which to be sent over the HTTP connection * @return status of the HTTP Put method execution */ public String putRaw(String Uri, String filePath) { initialize(); HttpPut request = new HttpPut(); try { requestUri = new URI(Uri); } catch (URISyntaxException e) { e.printStackTrace(); } setCredentials(); request.setURI(requestUri); Log.d("Request URL", Uri); try { File file = new File(filePath); FileEntity fe = new FileEntity(file, "/"); request.setEntity(fe); // request.setHeader("Content-Type","application/xml;charset=UTF-8"); response = client.execute(request); Log.d("Response status", response.getStatusLine().toString()); return response.getStatusLine().toString(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "error"; }
From source file:com.cellbots.httpserver.HttpCommandServer.java
public void handle(final HttpServerConnection conn, final HttpContext context) throws HttpException, IOException { HttpRequest request = conn.receiveRequestHeader(); HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"); String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") && !method.equals("PUT")) { throw new MethodNotSupportedException(method + " method not supported"); }/*from ww w .j a va 2 s . c o m*/ // Get the requested target. This is the string after the domain name in // the URL. If the full URL was http://mydomain.com/test.html, target // will be /test.html. String target = request.getRequestLine().getUri(); //Log.w(TAG, "*** Request target: " + target); // Gets the requested resource name. For example, if the full URL was // http://mydomain.com/test.html?x=1&y=2, resource name will be // test.html final String resName = getResourceNameFromTarget(target); UrlParams params = new UrlParams(target); //Log.w(TAG, "*** Request LINE: " + request.getRequestLine().toString()); //Log.w(TAG, "*** Request resource: " + resName); if (method.equals("POST") || method.equals("PUT")) { byte[] entityContent = null; // Gets the content if the request has an entity. if (request instanceof HttpEntityEnclosingRequest) { conn.receiveRequestEntity((HttpEntityEnclosingRequest) request); HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { entityContent = EntityUtils.toByteArray(entity); } } response.setStatusCode(HttpStatus.SC_OK); if (serverListener != null) { serverListener.onRequest(resName, params.keys, params.values, entityContent); } } else if (dataMap.containsKey(resName)) { // The requested resource is // a byte array response.setStatusCode(HttpStatus.SC_OK); response.setHeader("Content-Type", dataMap.get(resName).contentType); response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource)); } else { // Resource is a file recognized by the app String fileName = resourceMap.containsKey(resName) ? resourceMap.get(resName).resource : resName; String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType : "text/html"; Log.d(TAG, "*** mapped resource: " + fileName); Log.d(TAG, "*** checking for file: " + rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName); response.setStatusCode(HttpStatus.SC_OK); final File file = new File(rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName); if (file.exists() && !file.isDirectory()) { response.setStatusCode(HttpStatus.SC_OK); FileEntity body = new FileEntity(file, URLConnection.guessContentTypeFromName(fileName)); response.setHeader("Content-Type", URLConnection.guessContentTypeFromName(fileName)); response.setEntity(body); } else if (file.isDirectory()) { response.setStatusCode(HttpStatus.SC_OK); EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); ArrayList<String> fileList = getDirListing(file); String resp = "{ \"list\": ["; for (String fl : fileList) { resp += "\"" + fl + "\","; } resp = resp.substring(0, resp.length() - 1); resp += "]}"; writer.write(resp); writer.flush(); } }); body.setContentType(contentType); response.setEntity(body); } else if (resourceMap.containsKey(resName)) { EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write(resourceMap.get(resName).resource); writer.flush(); } }); body.setContentType(contentType); response.setEntity(body); } else { response.setStatusCode(HttpStatus.SC_NOT_FOUND); response.setEntity(new StringEntity("Not Found")); } } conn.sendResponseHeader(response); conn.sendResponseEntity(response); conn.flush(); conn.shutdown(); }
From source file:org.apache.tuscany.sca.binding.atom.MediaCollectionTestCase.java
@Test public void testMediaEntryPutNotFound() throws Exception { // Pseudo Code (see APP (http://tools.ietf.org/html/rfc5023#section-9.6) // Testing of entry update String receiptName = "Value Autoglass Bill"; String fileName = "target/test-classes/ReceiptValue.jpg"; File input = new File(fileName); boolean exists = input.exists(); Assert.assertTrue(exists);//from w ww .j a va 2 s . co m // Prepare HTTP put request // PUT /edit/the_beach.png HTTP/1.1 // Host: media.example.org // Content-Type: image/png // Content-Length: nnn // ...binary data... HttpPut put = new HttpPut(providerURI + "/" + mediaId + "-bogus"); // Does not exist. put.addHeader("Content-Type", "image/jpg"); put.addHeader("Title", "Title " + receiptName + ""); put.addHeader("Slug", "Slug " + receiptName + ""); put.setEntity(new FileEntity(input, "image/jpg")); // Get HTTP client HttpClient httpclient = new HttpClientFactory().createHttpClient(); try { // Execute request HttpResponse response = httpclient.execute(put); int result = response.getStatusLine().getStatusCode(); // Pseudo Code (see APP (http://tools.ietf.org/html/rfc5023#section-9.6) // Display status code // System.out.println("Response status code: " + result + ", status text=" + put.getStatusText() ); Assert.assertEquals(404, result); // Display response. Should be empty for put. // System.out.println("Response body: "); // System.out.println(put.getResponseBodyAsString()); // Warning: BodyAsString recommends BodyAsStream } finally { // Release current connection to the connection pool once you are done // put.releaseConnection(); } }
From source file:com.buffalokiwi.api.API.java
/** * Perform a put-based request to some endpoint * @param url URL// w w w. ja v a 2s .c om * @param file file to send * @param headers additional headers * @return response * @throws APIException */ @Override public IAPIResponse put(final String url, final PostFile file, Map<String, String> headers) throws APIException { final FileEntity entity = new FileEntity(file.getFile(), file.getContentType()); if (file.hasContentEncoding()) entity.setContentEncoding(file.getContentEncoding()); //..Create the new put request final HttpPut put = (HttpPut) createRequest(HttpMethod.PUT, url, headers); //..Set the put payload put.setEntity(entity); APILog.trace(LOG, entity.toString()); //..Execute the request return executeRequest(put); }
From source file:me.code4fun.roboq.Request.java
private HttpEntity createBody(Object o) { Object o1 = o instanceof Body ? ((Body) o).content : o; String c1 = o instanceof Body ? ((Body) o).contentType : null; if (o1 instanceof byte[]) { ByteArrayEntity entity = new ByteArrayEntity((byte[]) o1) { @Override/*from ww w .j a v a 2 s.c o m*/ public void writeTo(OutputStream outstream) throws IOException { super.writeTo(decorateBodyOutput(outstream)); } }; entity.setContentType(c1 != null ? c1 : DEFAULT_BINARY_CONTENT_TYPE); return entity; } else if (o1 instanceof InputStream) { Long len = o instanceof Body ? ((Body) o).length : null; if (len == null) throw new RoboqException("Missing length in body for upload InputStream"); InputStreamEntity entity = new InputStreamEntity((InputStream) o1, len) { @Override public void writeTo(OutputStream outstream) throws IOException { super.writeTo(decorateBodyOutput(outstream)); } }; entity.setContentType(c1 != null ? c1 : DEFAULT_BINARY_CONTENT_TYPE); return entity; } else if (o1 instanceof File) { File f = (File) o1; return new FileEntity(f, c1 != null ? c1 : getFileContentType(f)) { @Override public void writeTo(OutputStream outstream) throws IOException { super.writeTo(decorateBodyOutput(outstream)); } }; } else { String s = o2s(o1, ""); String encoding = selectValue(fieldsEncoding, prepared != null ? prepared.fieldsEncoding : null, "UTF-8"); try { StringEntity entity; entity = new StringEntity(s, encoding) { @Override public void writeTo(OutputStream outstream) throws IOException { super.writeTo(decorateBodyOutput(outstream)); } }; entity.setContentType(c1 != null ? c1 : DEFAULT_TEXT_CONTENT_TYPE); return entity; } catch (UnsupportedEncodingException e) { throw new RoboqException("Illegal encoding for request body", e); } } }