List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:dk.i2m.drupal.resource.FileResource.java
private MultipartEntity getMultipartEntity(File file, String fileName) throws MimeTypeException, IOException { TikaConfig tikaConfig = TikaConfig.getDefaultConfig(); MimeTypes mimeTypes = tikaConfig.getMimeRepository(); byte[] buf = IOUtils.toByteArray(new FileInputStream(file)); InputStream in = new ByteArrayInputStream(buf); MediaType mediaType = mimeTypes.detect(in, new Metadata()); MimeType mimeType = mimeTypes.forName(mediaType.toString()); MultipartEntity multipartEntity = new MultipartEntity(); int x = 0;// ww w .j av a 2 s.co m FileBody fb = new FileBody(file, fileName + mimeType.getExtension(), mimeType.getName(), Consts.UTF_8.name()); multipartEntity.addPart("files[" + x + "]", fb); return multipartEntity; }
From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java
/** * Sends data to create and train a classifier, and returns information about the new * classifier. The status has the value of `Training` when the operation is * successful, and might remain at this status for a while. * * @param name the classifier name * @param language IETF primary language for the classifier * @param csvTrainingData the CSV training data * @return the classifier/* ww w .j a v a2s .com*/ * @see Classifier */ public Classifier createClassifier(final String name, final String language, final File csvTrainingData) { if (csvTrainingData == null || !csvTrainingData.exists()) throw new IllegalArgumentException("csvTrainingData can not be null or not be found"); JsonObject contentJson = new JsonObject(); contentJson.addProperty("language", language == null ? LANGUAGE_EN : language); if (name != null && !name.isEmpty()) { contentJson.addProperty("name", name); } try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("training_data", new FileBody(csvTrainingData)); reqEntity.addPart("training_metadata", new StringBody(contentJson.toString())); HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build(); HttpHost proxy = new HttpHost("10.100.1.124", 3128); ConnRouteParams.setDefaultProxy(request.getParams(), proxy); HttpResponse response = execute(request); return ResponseUtil.getObject(response, Classifier.class); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:functionaltests.RestSchedulerPushPullFileTest.java
public void testIt(String spaceName, String spacePath, String destPath, boolean encode) throws Exception { File testPushFile = RestFuncTHelper.getDefaultJobXmlfile(); // you can test pushing pulling a big file : // testPushFile = new File("path_to_a_big_file"); File destFile = new File(new File(spacePath, destPath), testPushFile.getName()); if (destFile.exists()) { destFile.delete();//from w ww . ja v a2s . c om } // PUSHING THE FILE String pushfileUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/"))); // either we encode or we test human readable path (with no special character inside) HttpPost reqPush = new HttpPost(pushfileUrl); setSessionHeader(reqPush); // we push a xml job as a simple test MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("fileName", new StringBody(testPushFile.getName())); multipartEntity.addPart("fileContent", new InputStreamBody(FileUtils.openInputStream(testPushFile), MediaType.APPLICATION_OCTET_STREAM, null)); reqPush.setEntity(multipartEntity); HttpResponse response = executeUriRequest(reqPush); System.out.println(response.getStatusLine()); assertHttpStatusOK(response); Assert.assertTrue(destFile + " exists for " + spaceName, destFile.exists()); Assert.assertTrue("Original file and result are equals for " + spaceName, FileUtils.contentEquals(testPushFile, destFile)); // LISTING THE TARGET DIRECTORY String pullListUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/"))); HttpGet reqPullList = new HttpGet(pullListUrl); setSessionHeader(reqPullList); HttpResponse response2 = executeUriRequest(reqPullList); System.out.println(response2.getStatusLine()); assertHttpStatusOK(response2); InputStream is = response2.getEntity().getContent(); List<String> lines = IOUtils.readLines(is); HashSet<String> content = new HashSet<>(lines); System.out.println(lines); Assert.assertTrue("Pushed file correctly listed", content.contains(testPushFile.getName())); // PULLING THE FILE String pullfileUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath + "/" + testPushFile.getName(), "UTF-8") : destPath.replace("\\", "/") + "/" + testPushFile.getName())); HttpGet reqPull = new HttpGet(pullfileUrl); setSessionHeader(reqPull); HttpResponse response3 = executeUriRequest(reqPull); System.out.println(response3.getStatusLine()); assertHttpStatusOK(response3); InputStream is2 = response3.getEntity().getContent(); File answerFile = tmpFolder.newFile(); FileUtils.copyInputStreamToFile(is2, answerFile); Assert.assertTrue("Original file and result are equals for " + spaceName, FileUtils.contentEquals(answerFile, testPushFile)); // DELETING THE HIERARCHY String rootPath = destPath.substring(0, destPath.contains("/") ? destPath.indexOf("/") : destPath.length()); String deleteUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(rootPath, "UTF-8") : rootPath.replace("\\", "/"))); HttpDelete reqDelete = new HttpDelete(deleteUrl); setSessionHeader(reqDelete); HttpResponse response4 = executeUriRequest(reqDelete); System.out.println(response4.getStatusLine()); assertHttpStatusOK(response4); Assert.assertTrue(destFile + " still exist", !destFile.exists()); }
From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java
/** * Sends data to create and train a classifier, and returns information about the new * classifier. The status has the value of `Training` when the operation is * successful, and might remain at this status for a while. * /*from www . ja v a 2s . c om*/ * @param name * the classifier name * @param language * IETF primary language for the classifier * @param trainingData * The set of questions and their "keys" used to adapt a system to a domain * (the ground truth) * @return the classifier * @see Classifier */ public Classifier createClassifier(final String name, final String language, final List<TrainingData> trainingData) { if (trainingData == null || trainingData.isEmpty()) throw new IllegalArgumentException("trainingData can not be null or empty"); JsonObject contentJson = new JsonObject(); contentJson.addProperty("language", language == null ? LANGUAGE_EN : language); if (name != null && !name.isEmpty()) { contentJson.addProperty("name", name); } try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("training_data", new StringBody(TrainingDataUtils.toCSV(trainingData.toArray(new TrainingData[0])))); reqEntity.addPart("training_metadata", new StringBody(contentJson.toString())); HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build(); HttpHost proxy = new HttpHost("10.100.1.124", 3128); ConnRouteParams.setDefaultProxy(request.getParams(), proxy); HttpResponse response = execute(request); return ResponseUtil.getObject(response, Classifier.class); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java
@Test public void testMultiPartRequest() throws IOException { TestHttpClient client = new TestHttpClient(); try {/*from w ww. j a v a2 s .co m*/ String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1"; HttpPost post = new HttpPost(uri); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, StandardCharsets.UTF_8); entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8)); entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile()))); post.setEntity(entity); HttpResponse result = client.execute(post); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); final String response = HttpClientUtils.readResponse(result); Assert.assertEquals("PARAMS:\n" + "name: formValue\n" + "filename: null\n" + "content-type: null\n" + "Content-Disposition: form-data; name=\"formValue\"\n" + "size: 7\n" + "content: myValue\n" + "name: file\n" + "filename: uploadfile.txt\n" + "content-type: application/octet-stream\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n" + "Content-Type: application/octet-stream\n" + "size: 13\n" + "content: file contents\n", response); } finally { client.getConnectionManager().shutdown(); } }
From source file:de.uzk.hki.da.webservice.HttpFileTransmissionClient.java
/** * Post file.//from ww w . ja v a 2 s . c o 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:com.urucas.services.JSONFileRequest.java
@SuppressWarnings("deprecation") @Override//from w w w .j a v a 2 s .c om protected String doInBackground(String... uri) { HttpClient httpclient = new DefaultHttpClient(); // add request params StringBuffer url = new StringBuffer(uri[0]).append("?") .append(URLEncodedUtils.format(getParams(), "UTF-8")); HttpPost _post = new HttpPost(url.toString()); HttpContext localContext = new BasicHttpContext(); Log.i("url ---->", url.toString()); MultipartEntity _entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < getParams().size(); index++) { try { _entity.addPart(getParams().get(index).getName(), new StringBody(getParams().get(index).getValue())); } catch (UnsupportedEncodingException e) { } } _entity.addPart("imagen", new FileBody(file)); _post.setEntity(_entity); HttpResponse response; String responseString = null; // execute try { response = httpclient.execute(_post, localContext); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); responseString = out.toString(); if (isCancelled()) { rsh.onError("Task cancel"); } } else { //Closes the connection. response.getEntity().getContent().close(); Log.i("status", String.valueOf(statusLine.getStatusCode())); throw new IOException(statusLine.getReasonPhrase()); } } catch (ClientProtocolException e) { e.printStackTrace(); //rsh.onError(e.getMessage()); } catch (IOException e) { e.printStackTrace(); //rsh.onError(e.getMessage()); } return responseString; }
From source file:eu.liveGov.libraries.livegovtoolkit.Utils.RestClient.java
public void Execute(RequestMethod method, int soTime, int connTime) throws Exception { switch (method) { case GET: {//from w w w .java 2s .c o m // add parameters String combinedParams = ""; if (!params.isEmpty()) { combinedParams += "?"; for (NameValuePair p : params) { String paramString; paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8"); if (combinedParams.length() > 1) { combinedParams += "&" + paramString; } else { combinedParams += paramString; } } } HttpGet request = new HttpGet(url + combinedParams); // add headers for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } executeRequest(request, url, soTime, connTime); break; } case POST: { HttpPost request = new HttpPost(url); // add headers for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } if (!_json.isEmpty()) { request.addHeader("Content-type", "application/json"); request.setEntity(new StringEntity(_json, "UTF8")); } else if (!params.isEmpty()) { request.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); } executeRequest(request, url, soTime, connTime); break; } case POSTLOG: { HttpPost request = new HttpPost(url); // add headers for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } MultipartEntity reqEntity = new MultipartEntity(); if (!_json.isEmpty()) { reqEntity.addPart("LogfileRequest", new StringBody(_json, "application/json", Charset.forName("UTF-8"))); } else if (!params.isEmpty()) { // ignore the params for now. } if (_file != null) { reqEntity.addPart("logfile", new FileBody(_file)); } request.setEntity(reqEntity); executeRequest(request, url, soTime, connTime); break; } } }
From source file:com.grouzen.android.serenity.HttpConnection.java
private HttpResponse post(String url, Bundle params) throws ClientProtocolException, IOException { HttpPost method = new HttpPost(url); if (params != null) { try {// www . ja v a 2 s. c o m if (mMultipartKey != null && mMultipartFileName != null) { ByteArrayBody byteArrayBody = new ByteArrayBody(params.getByteArray(mMultipartKey), mMultipartFileName); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); Charset charset = Charset.forName(CHARSET); entity.addPart(mMultipartKey, byteArrayBody); params.remove(mMultipartKey); for (String k : params.keySet()) { entity.addPart(new FormBodyPart(k, new StringBody(params.getString(k), charset))); } method.setEntity(entity); } else { ArrayList<NameValuePair> entity = convertParams(params); method.setEntity(new UrlEncodedFormEntity(entity, CHARSET)); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return execute(method); }