List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file, final String mimeType)
From source file:org.apache.heron.uploader.http.HttpUploader.java
private URI uploadPackageAndGetURI(final CloseableHttpClient httpclient) throws IOException, URISyntaxException { File file = new File(this.topologyPackageLocation); String uploaderUri = HttpUploaderContext.getHeronUploaderHttpUri(this.config); post = new HttpPost(uploaderUri); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(FILE, fileBody);/*from w ww . ja v a 2s . c o m*/ HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse response = execute(httpclient); String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.name()); LOG.fine("Topology package download URI: " + responseString); return new URI(responseString); }
From source file:jp.canetrash.maven.plugin.bijint.BujintMojo.java
/** * @param image/*from w ww . j a v a2 s . c o m*/ * @return * @throws IOException * @throws ClientProtocolException * @throws UnsupportedEncodingException */ private String getAsciiArt(BufferedImage image) throws IOException, ClientProtocolException, UnsupportedEncodingException { File tmpfile = File.createTempFile("bjint_", ".jpg"); ImageIO.write(image, "jpg", tmpfile); // http://picascii.com/???? // ????? DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://picascii.com/"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); entity.consumeContent(); // ??? HttpPost httppost = new HttpPost("http://picascii.com/upload.php"); //HttpPost httppost = buildDefaultHttpMessage(new HttpPost("http://localhost:8080/sa-struts-tutorial/upload/")); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(tmpfile, "image/jpeg"); reqEntity.addPart("imageupload", bin); reqEntity.addPart("MAX_FILE_SIZE", new StringBody("1000000")); reqEntity.addPart("url", new StringBody("")); reqEntity.addPart("quality", new StringBody("3")); reqEntity.addPart("size", new StringBody("1")); httppost.setEntity(reqEntity); response = httpclient.execute(httppost); String responseHtml = IOUtils.toString(response.getEntity().getContent()); httpclient.getConnectionManager().shutdown(); // tmpFile? tmpfile.delete(); return bringOutAsciiArtString(responseHtml); }
From source file:com.huawei.ais.demo.TokenDemo.java
/** * Base64???Token???/* ww w .j av a 2 s.c om*/ * @param token token? * @param formFile * @throws IOException */ public static void requestOcrCustomsFormEnBase64(String token, String formFile) { // 1.????? String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/action/ocr_form"; Header[] headers = new Header[] { new BasicHeader("X-Auth-Token", token) }; try { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody fileBody = new FileBody(new File(formFile), ContentType.create("image/jpeg", "utf-8")); multipartEntityBuilder.addPart("file", fileBody); // 2.????, POST?? HttpResponse response = HttpClientUtils.post(url, headers, multipartEntityBuilder.build()); System.out.println(response); String content = IOUtils.toString(response.getEntity().getContent()); System.out.println(content); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.cottsoft.weedfs.client.WeedfsClient.java
/** * Description<br>//from w w w . j ava 2s . c o m * Cache local file to WeedFS Server * * @version v1.0.0 * @param file * @return */ public RequestResult cache(File file) { RequestResult result = null; Gson gson = new Gson(); if (!file.exists()) { throw new IllegalArgumentException("File doesn't exist"); } // HTTP REQUEST begin result = new RequestResult(); WeedAssign assignedInfo = null; BufferedReader in = null; // 1. Send assign request and get fid try { StringBuffer host = new StringBuffer(); host.append("http://"); host.append(this.masterHost); host.append(":"); host.append(this.masterPort); host.append("/"); //HttpUtil.request("http://" + this.masterHost + ":" + this.masterPort+ "/", "dir/assign", "GET") in = new BufferedReader( new InputStreamReader(HttpUtil.request(host.toString(), assign, EHttpMethod.GET))); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } // format HTTP Response to Assigned Info. assignedInfo = gson.fromJson(response.toString(), WeedAssign.class); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } finally { try { // close input stream. if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } // 2. Send cache file request on volume server FileBody fileBody = new FileBody(file, "text/plain"); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); StringBuffer uri = new StringBuffer(); uri.append("http://"); uri.append(assignedInfo.getPublicUrl()); uri.append("/"); uri.append(assignedInfo.getFid()); HttpPost post = new HttpPost(uri.toString()); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("fileBody", fileBody); post.setEntity(entity); try { // Add File char. String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); client.getConnectionManager().shutdown(); FileResult fileResult = gson.fromJson(response, FileResult.class); result.setFid(assignedInfo.getFid()); result.setSize(fileResult.getSize()); result.setStatus(true); result.setFileUrl(uri.toString()); return result; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.toString()); } }
From source file:de.uzk.hki.da.webservice.HttpFileTransmissionClient.java
/** * Post file./* w w w .j a v a2s. co m*/ * * @param file the file * @param toFile the to file */ @SuppressWarnings("finally") public File postFileAndReadResponse(File file, File toFile) { HttpClient httpclient = null; ; try { if (!file.exists()) { throw new RuntimeException("Source File does not exist " + file.getAbsolutePath()); } if (url.isEmpty()) { throw new RuntimeException("Webservice called but Url is empty"); } httpclient = new DefaultHttpClient(); logger.info("starting new http client for url " + url); HttpPost httppost = new HttpPost(url); HttpParams httpRequestParameters = httppost.getParams(); httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, true); httppost.setParams(httpRequestParameters); MultipartEntity multiPartEntity = new MultipartEntity(); multiPartEntity.addPart("fileDescription", new StringBody("doxc Converison")); multiPartEntity.addPart("fileName", new StringBody(file.getName())); if (sourceMimeType.isEmpty()) sourceMimeType = "application/octet-stream"; if (destMimeType.isEmpty()) destMimeType = "application/octet-stream"; FileBody fileBody = new FileBody(file, sourceMimeType); multiPartEntity.addPart("attachment", fileBody); httppost.setEntity(multiPartEntity); logger.debug("calling webservice now. recieving response"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == 200 && resEntity.getContentType().getValue().startsWith(destMimeType)) { InputStream in = resEntity.getContent(); FileOutputStream fos = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0) { fos.write(buffer, 0, length); } logger.debug("successfully stored recieved content to " + toFile.getAbsolutePath()); in.close(); fos.close(); cleanup(); } else { logger.error( "Recieved reponse of " + resEntity.getContentType() + ", but expected " + destMimeType); printResponse(resEntity); } } catch (Exception e) { logger.error("Exception occured in remotefileTransmission " + e.getStackTrace()); throw new RuntimeException("Webservice error " + url, e); } finally { if (httpclient != null) httpclient.getConnectionManager().shutdown(); return toFile; } }
From source file:net.ladenthin.snowman.imager.run.uploader.Uploader.java
@Override public void run() { final CImager cs = ConfigurationSingleton.ConfigurationSingleton.getImager(); final String url = cs.getSnowmanServer().getApiUrl(); for (;;) {/*from w w w . j a v a 2 s . c o m*/ File obtainedFile; for (;;) { if (WatchdogSingleton.WatchdogSingleton.getWatchdog().getKillFlag() == true) { LOGGER.trace("killFlag == true"); return; } obtainedFile = FileAssignationSingleton.FileAssignationSingleton.obtainFile(); if (obtainedFile == null) { Imager.waitALittleBit(300); continue; } else { break; } } boolean doUpload = true; while (doUpload) { try { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { final HttpPost httppost = new HttpPost(url); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final FileBody fb = new FileBody(obtainedFile, ContentType.APPLICATION_OCTET_STREAM); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(uploadNameCameraimage, fb); builder.addTextBody(uploadNameFilename, obtainedFile.getName()); builder.addTextBody(uploadNameUsername, cs.getSnowmanServer().getUsername()); builder.addTextBody(uploadNamePassword, cs.getSnowmanServer().getPassword()); builder.addTextBody(uploadNameCameraname, cs.getSnowmanServer().getCameraname()); final HttpEntity httpEntity = builder.build(); httppost.setEntity(httpEntity); if (LOGGER.isTraceEnabled()) { LOGGER.trace("executing request " + httppost.getRequestLine()); } try (CloseableHttpResponse response = httpclient.execute(httppost)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("response.getStatusLine(): " + response.getStatusLine()); } final HttpEntity resEntity = response.getEntity(); if (resEntity != null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("RresEntity.getContentLength(): " + resEntity.getContentLength()); } } final String resString = EntityUtils.toString(resEntity).trim(); EntityUtils.consume(resEntity); if (resString.equals(responseSuccess)) { doUpload = false; LOGGER.trace("true: resString.equals(responseSuccess)"); LOGGER.trace("resString: {}", resString); } else { LOGGER.warn("false: resString.equals(responseSuccess)"); LOGGER.warn("resString: {}", resString); // do not flood log files if an error occurred Imager.waitALittleBit(2000); } } } } catch (NoHttpResponseException | SocketException e) { logIOExceptionAndWait(e); } catch (IOException e) { LOGGER.warn("Found unknown IOException", e); } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("delete obtainedFile {}", obtainedFile); } final boolean delete = obtainedFile.delete(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("delete success {}", delete); } FileAssignationSingleton.FileAssignationSingleton.freeFile(obtainedFile); } }
From source file:com.rackspace.api.clients.veracode.DefaultVeracodeApiClient.java
private String uploadFile(File file, int buildVersion, String appId, String platfrom) throws VeracodeApiException { HttpPost post = new HttpPost(baseUri.resolve(UPLOAD)); MultipartEntity entity = new MultipartEntity(); try {// w w w . j av a2s. c om entity.addPart(new FormBodyPart("app_id", new StringBody(appId))); entity.addPart(new FormBodyPart("version", new StringBody(String.valueOf(buildVersion)))); entity.addPart(new FormBodyPart("platform", new StringBody(platfrom))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("The Request could not be made due to an encoding issue", e); } entity.addPart("file", new FileBody(file, "text/plain")); post.setEntity(entity); logger.println("Executing Request: " + post.getRequestLine()); UploadResponse uploadResponse = null; try { uploadResponse = new UploadResponse(client.execute(post)); } catch (IOException e) { throw new VeracodeApiException("The call to Veracode failed.", e); } return uploadResponse.getBuildId(buildVersion); }
From source file:me.ziccard.secureit.async.AudioRecorderTask.java
@Override public void run() { MicrophoneTaskFactory.pauseSampling(); while (MicrophoneTaskFactory.isSampling()) { try {/* w ww . j a v a 2 s.co m*/ Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } recording = true; final MediaRecorder recorder = new MediaRecorder(); ContentValues values = new ContentValues(3); values.put(MediaStore.MediaColumns.TITLE, filename); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); String audioPath = Environment.getExternalStorageDirectory().getPath() + filename + ".m4a"; recorder.setOutputFile(audioPath); try { recorder.prepare(); } catch (Exception e) { e.printStackTrace(); return; } Log.i("AudioRecorderTask", "Start recording"); recorder.start(); try { Thread.sleep(prefs.getAudioLenght()); } catch (InterruptedException e) { e.printStackTrace(); } recorder.stop(); Log.i("AudioRecorderTask", "Stopped recording"); recorder.release(); recording = false; MicrophoneTaskFactory.restartSampling(); /* * Uploading the audio */ Log.i("AudioRecorderTask", "Trying to upload"); HttpClient httpclient = new DefaultHttpClient(); HttpPost request = new HttpPost(Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_AUDIO); Log.i("AudioRecorderTask", "URI: " + Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_AUDIO); /* * Getting the audio from the file system */ MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File audio = new File(audioPath); reqEntity.addPart("audio", new FileBody(audio, "audio/mp3")); request.setEntity(reqEntity); /* * Authentication token */ request.setHeader("access_token", accessToken); try { HttpResponse response = httpclient.execute(request); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } Log.i("AudioRecorderTask", "Response:\n" + builder.toString()); if (response.getStatusLine().getStatusCode() != 200) { Log.i("AudioRecorderTask", "Error uploading audio: " + audioPath); throw new HttpException(); } } catch (Exception e) { Log.e("DataUploaderTask", "Error uploading audio: " + audioPath); } }
From source file:org.craftercms.social.util.UGCHttpClient.java
private HttpPost manageAttachments(String[] attachments, String ticket, String target, String textContent) throws UnsupportedEncodingException, URISyntaxException { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("ticket", ticket)); URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/ugc/" + "create.json", URLEncodedUtils.format(qparams, HTTP.UTF_8), null); HttpPost httppost = new HttpPost(uri); if (attachments.length > 0) { MultipartEntity me = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file;// ww w. j ava 2s .co m FileBody fileBody; for (String f : attachments) { file = new File(f); fileBody = new FileBody(file, "application/octect-stream"); me.addPart("attachments", fileBody); } //File file = new File(attachments[0]); //FileBody fileBody = new FileBody(file, "application/octect-stream") ; //me.addPart("attachments", fileBody) ; me.addPart("target", new StringBody(target)); me.addPart("textContent", new StringBody(textContent)); httppost.setEntity(me); } return httppost; }
From source file:com.ibm.watson.developer_cloud.document_conversion.v1.helpers.DocumentHelper.java
/** * Uploads the document to the store with the given media type * /*from ww w. ja va 2s. co m*/ * POST /v1/documents. * * @param document the document to be uploaded * @param mediaType the Internet media type for the file * @return Document * @see DocumentConversion#uploadDocument(File, String) */ public Document uploadDocument(final File document, final String mediaType) { if (mediaType == null || mediaType.isEmpty()) throw new IllegalArgumentException("media type cannot be null or empty"); if (!ConversionUtils.isValidMediaType(mediaType)) throw new IllegalArgumentException("file with the given media type is not supported"); if (document == null || !document.exists()) throw new IllegalArgumentException("document cannot be null and must exist"); try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(document, mediaType)); HttpRequestBase request = Request.Post(ConfigConstants.DOCUMENTS_PATH).withEntity(reqEntity).build(); HttpResponse response = docConversionService.execute(request); String documentAsJson = ResponseUtil.getString(response); Document doc = GsonSingleton.getGson().fromJson(documentAsJson, Document.class); return doc; } catch (IOException e) { throw new RuntimeException(e); } }