List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:com.ibm.watson.developer_cloud.document_conversion.v1.helpers.ConvertDocumentHelper.java
/** * Synchronously converts a new document without persistence * POST /v1/convert_document./*from www .j a va 2s . c om*/ * * @param document The file to convert * @param mediaType Internet media type for the file * @param conversionTarget The conversion target to use * @return Converted document in the specified format * @see DocumentConversion#convertDocument(File, String, ConversionTarget) */ public InputStream convertDocument(final File document, String mediaType, final ConversionTarget conversionTarget) { 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 can not be null and must exist"); if (conversionTarget == null) throw new IllegalArgumentException("conversion target can not be null"); try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(document, mediaType)); JsonObject configRequestJson = new JsonObject(); configRequestJson.addProperty("conversion_target", conversionTarget.toString()); String json = configRequestJson.toString(); reqEntity.addPart("config", new StringBody(json, MediaType.APPLICATION_JSON, Charset.forName("UTF-8"))); HttpRequestBase request = Request.Post(ConfigConstants.CONVERT_DOCUMENT_PATH).withEntity(reqEntity) .build(); HttpResponse response = docConversionService.execute(request); InputStream is = ResponseUtil.getInputStream(response); return is; } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.deviceconnect.android.manager.test.MultipartTest.java
/** * 0?????????./*from w ww .j a v a 2 s .c o m*/ * <pre> * Method: POST * Path: /file/send?deviceid=xxxx&filename=xxxx * </pre> * <pre> * ?? * result?0??????? * </pre> */ public void testSendZeroByteFile() { URIBuilder builder = TestURIBuilder.createURIBuilder(); builder.setProfile(FileProfileConstants.PROFILE_NAME); builder.setAttribute(FileProfileConstants.ATTRIBUTE_SEND); builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, getDeviceId()); builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken()); builder.addParameter(FileProfileConstants.PARAM_PATH, "/test/zero.dat"); builder.addParameter(FileProfileConstants.PARAM_FILE_TYPE, String.valueOf(FileProfileConstants.FileType.FILE.getValue())); try { MultipartEntity entity = new MultipartEntity(); // ?0?? entity.addPart(FileProfileConstants.PARAM_DATA, new BinaryBody(new byte[] {}, "zero.dat")); HttpPost request = new HttpPost(builder.toString()); request.setEntity(entity); JSONObject root = sendRequest(request); assertResultOK(root); } catch (JSONException e) { fail("Exception in JSONObject." + e.getMessage()); } }
From source file:hu.sztaki.lpds.dcibridge.util.io.HttpHandler.java
public void write(String pURL, List<File> pValue) throws IOException { open(pURL);/*from w w w. ja v a 2s . c o m*/ MultipartEntity reqEntity = new MultipartEntity(); for (File t : pValue) { FileBody bin = new FileBody(t); reqEntity.addPart(t.getName(), bin); } httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); }
From source file:com.onaio.steps.helper.UploadFileTask.java
@Override protected Boolean doInBackground(File... files) { if (!TextUtils.isEmpty(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL))) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL)); try {/*from w ww. ja v a 2 s . c om*/ MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")); multipartEntity.addPart("file", new FileBody(files[0])); httpPost.setEntity(multipartEntity); httpClient.execute(httpPost); new CustomNotification().notify(activity, R.string.export_complete, R.string.export_complete_message); return true; } catch (IOException e) { new Logger().log(e, "Export failed."); new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed); } } else { new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed); } return false; }
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 * //w w w. jav a 2 s. c om * 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); } }
From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java
@Test public void testFileUploadWithEagerParsingAndNonASCIIFilename() throws Exception { DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler())); TestHttpClient client = new TestHttpClient(); try {// www. j a va2s.co m HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path"); MultipartEntity entity = new MultipartEntity(); entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8)); File uploadfile = new File( MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile()); FormBodyPart filePart = new FormBodyPart("file", new FileBody(uploadfile, "", "application/octet-stream", Charsets.UTF_8.toString())); filePart.addField("Content-Disposition", "form-data; name=\"file\"; filename*=\"utf-8''%CF%84%CE%B5%CF%83%CF%84.txt\""); entity.addPart(filePart); post.setEntity(entity); HttpResponse result = client.execute(post); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.revo.deployr.client.call.repository.RepositoryDirectoryUploadCall.java
/** * Internal use only, to execute call use RClient.execute(). *//* w w w .j ava2s . co m*/ public RCoreResult call() { RCoreResultImpl pResult = null; try { HttpPost httpPost = new HttpPost(serverUrl + API); super.httpUriRequest = httpPost; List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new BasicNameValuePair("format", "json")); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("file", new InputStreamBody(((InputStream) zipStream), "application/zip")); if (options.directory != null) entity.addPart("directory", new StringBody(options.directory, "text/plain", Charset.forName("UTF-8"))); if (options.descr != null) entity.addPart("descr", new StringBody(options.descr, "text/plain", Charset.forName("UTF-8"))); entity.addPart("newversion", new StringBody(Boolean.toString(options.newversion), "text/plain", Charset.forName("UTF-8"))); if (options.restricted != null) entity.addPart("restricted", new StringBody(options.restricted, "text/plain", Charset.forName("UTF-8"))); entity.addPart("shared", new StringBody(Boolean.toString(options.shared), "text/plain", Charset.forName("UTF-8"))); entity.addPart("published", new StringBody(Boolean.toString(options.published), "text/plain", Charset.forName("UTF-8"))); if (options.inputs != null) entity.addPart("inputs", new StringBody(options.inputs, "text/plain", Charset.forName("UTF-8"))); if (options.outputs != null) entity.addPart("outputs", new StringBody(options.outputs, "text/plain", Charset.forName("UTF-8"))); entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8"))); httpPost.setEntity(entity); // set any custom headers on the request for (Map.Entry<String, String> entry : httpHeaders.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } HttpResponse response = httpClient.execute(httpPost); StatusLine statusLine = response.getStatusLine(); HttpEntity responseEntity = response.getEntity(); String markup = EntityUtils.toString(responseEntity); pResult = new RCoreResultImpl(response.getAllHeaders()); pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase()); } catch (UnsupportedEncodingException ueex) { log.warn("RepositoryDirectoryUploadCall: unsupported encoding exception.", ueex); } catch (IOException ioex) { log.warn("RepositoryDirectoryUploadCall: io exception.", ioex); } return pResult; }
From source file:com.github.mhendred.face4j.CopyOfResponderImpl.java
/** * @see {@link Responder#doPost(File, URI, List)} *//*from w ww. j av a2 s. c om*/ public String doPost(final File file, final URI uri, final List<NameValuePair> params) throws FaceClientException, FaceServerException { try { final MultipartEntity entity = new MultipartEntity(); entity.addPart("image", new FileBody(file)); try { for (NameValuePair nvp : params) { entity.addPart(nvp.getName(), new StringBody(nvp.getValue())); } } catch (UnsupportedEncodingException uee) { throw new FaceClientException(uee); } postMethod.setURI(uri); postMethod.setEntity(entity); final long start = System.currentTimeMillis(); final HttpResponse response = httpClient.execute(postMethod); return checkResponse(response); } catch (IOException ioe) { throw new FaceClientException(ioe); } }
From source file:com.google.appengine.tck.blobstore.support.FileUploader.java
public String uploadFile(String uri, String partName, String filename, String mimeType, byte[] contents, int expectedResponseCode) throws URISyntaxException, IOException { HttpClient httpClient = new DefaultHttpClient(); try {/*from w ww.j a va 2 s . com*/ HttpPost post = new HttpPost(uri); MultipartEntity entity = new MultipartEntity(); ByteArrayBody contentBody = new ByteArrayBody(contents, mimeType, filename); entity.addPart(partName, contentBody); post.setEntity(entity); HttpResponse response = httpClient.execute(post); String result = EntityUtils.toString(response.getEntity()); int statusCode = response.getStatusLine().getStatusCode(); Assert.assertEquals(String.format("Invalid response code, %s", statusCode), expectedResponseCode, statusCode); return result; } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:it.unipi.di.acube.batframework.systemPlugins.ERDSystem.java
@Override public HashSet<Tag> solveC2W(String text) throws AnnotationException { lastTime = Calendar.getInstance().getTimeInMillis(); HashSet<Tag> res = new HashSet<Tag>(); try {/* www . j a va 2 s. c o m*/ URL erdApi = new URL(url); HttpURLConnection connection = (HttpURLConnection) erdApi.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("runID", new StringBody(this.run)); multipartEntity.addPart("TextID", new StringBody("" + text.hashCode())); multipartEntity.addPart("Text", new StringBody(text)); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = ((HttpURLConnection) connection).getResponseCode(); if (status != 200) { BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String line = null; while ((line = br.readLine()) != null) System.err.println(line); throw new RuntimeException(); } BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = br.readLine()) != null) { String mid = line.split("\t")[2]; String title = freebApi.midToTitle(mid); int wid; if (title == null || (wid = wikiApi.getIdByTitle(title)) == -1) System.err.println("Discarding mid=" + mid); else res.add(new Tag(wid)); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } lastTime = Calendar.getInstance().getTimeInMillis() - lastTime; return res; }