List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity(HttpMultipartMode mode, final String boundary, final Charset charset)
From source file:no.digipost.android.api.ApiAccess.java
public static void uploadFile(Context context, String uri, File file) throws DigipostClientException { try {// ww w. j av a 2 s.com try { FileBody filebody = new FileBody(file, ApiConstants.CONTENT_OCTET_STREAM); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(ApiConstants.ENCODING)); multipartEntity.addPart("subject", new StringBody(FilenameUtils.removeExtension(file.getName()), ApiConstants.MIME, Charset.forName(ApiConstants.ENCODING))); multipartEntity.addPart("file", filebody); multipartEntity.addPart("token", new StringBody(TokenStore.getAccess())); URL url = new URL(uri); HttpsURLConnection httpsClient = (HttpsURLConnection) url.openConnection(); httpsClient.setRequestMethod("POST"); httpsClient.setDoOutput(true); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { httpsClient.setFixedLengthStreamingMode(multipartEntity.getContentLength()); } else { httpsClient.setChunkedStreamingMode(0); } httpsClient.setRequestProperty("Connection", "Keep-Alive"); httpsClient.addRequestProperty("Content-length", multipartEntity.getContentLength() + ""); httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION, ApiConstants.BEARER + TokenStore.getAccess()); httpsClient.addRequestProperty(multipartEntity.getContentType().getName(), multipartEntity.getContentType().getValue()); try { OutputStream outputStream = new BufferedOutputStream(httpsClient.getOutputStream()); multipartEntity.writeTo(outputStream); outputStream.flush(); NetworkUtilities.checkHttpStatusCode(context, httpsClient.getResponseCode()); } finally { httpsClient.disconnect(); } } catch (DigipostInvalidTokenException e) { OAuth.updateAccessTokenWithRefreshToken(context); uploadFile(context, uri, file); } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, context.getString(R.string.error_your_network)); throw new DigipostClientException(context.getString(R.string.error_your_network)); } }
From source file:org.trancecode.xproc.step.RequestParser.java
private MultipartEntity parseMultipart(final XdmNode requestNode, final Processor processor) { final XdmNode child = SaxonAxis.childElement(requestNode, XProcXmlModel.Elements.MULTIPART); if (child != null) { final String contentTypeAtt = child.getAttributeValue(XProcXmlModel.Attributes.CONTENT_TYPE); final String contentType = Strings.isNullOrEmpty(contentTypeAtt) ? DEFAULT_MULTIPART_TYPE : contentTypeAtt;/*from w ww .j a va2s . c om*/ final String boundary = child.getAttributeValue(XProcXmlModel.Attributes.BOUNDARY); if (StringUtils.startsWith(boundary, "--")) { throw XProcExceptions.xc0002(requestNode); } final MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT, boundary, Charset.forName("UTF-8")) { @Override protected String generateContentType(final String boundary, final Charset charset) { final StringBuilder buffer = new StringBuilder(); buffer.append(contentType).append("; boundary=").append(boundary); return buffer.toString(); } }; final Iterable<XdmNode> bodies = SaxonAxis.childElements(child, XProcXmlModel.Elements.BODY); for (final XdmNode body : bodies) { final FormBodyPart contentBody = getContentBody(body, processor); if (contentBody != null) { reqEntity.addPart(contentBody); } } return reqEntity; } return null; }
From source file:org.xmetdb.rest.protocol.attachments.CallableAttachmentImporter.java
protected HttpEntity createPOSTEntity(DBAttachment attachment) throws Exception { Charset utf8 = Charset.forName("UTF-8"); if ("text/uri-list".equals(attachment.getFormat())) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("title", attachment.getTitle())); formparams.add(new BasicNameValuePair("dataset_uri", attachment.getDescription())); formparams.add(new BasicNameValuePair("folder", attachment_type.substrate.equals(attachment.getType()) ? "substrate" : "product")); return new UrlEncodedFormEntity(formparams, "UTF-8"); } else {/*w w w . j a va 2s . c o m*/ if (attachment.getResourceURL() == null) throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Attachment resource URL is null! "); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8); entity.addPart("title", new StringBody(attachment.getTitle(), utf8)); entity.addPart("seeAlso", new StringBody(attachment.getDescription(), utf8)); entity.addPart("license", new StringBody("XMETDB", utf8)); entity.addPart("file", new FileBody(new File(attachment.getResourceURL().toURI()))); return entity; } //match, seeAlso, license }
From source file:org.bonitasoft.engine.api.HTTPServerAPI.java
final HttpEntity buildEntity(final Map<String, Serializable> options, final List<String> classNameParameters, final Object[] parametersValues, final XStream xstream) throws UnsupportedEncodingException, IOException { final HttpEntity httpEntity; /*// www. j a va2 s. c o m * if we have a business archive we use multipart to have the business archive attached as a binary content (it can be big) */ if (classNameParameters.contains(BusinessArchive.class.getName()) || classNameParameters.contains(byte[].class.getName())) { final List<Object> bytearrayParameters = new ArrayList<Object>(); final MultipartEntity entity = new MultipartEntity(null, null, UTF8); entity.addPart(OPTIONS, new StringBody(toXML(options, xstream), UTF8)); entity.addPart(CLASS_NAME_PARAMETERS, new StringBody(toXML(classNameParameters, xstream), UTF8)); for (int i = 0; i < parametersValues.length; i++) { final Object parameterValue = parametersValues[i]; if (parameterValue instanceof BusinessArchive || parameterValue instanceof byte[]) { parametersValues[i] = BYTE_ARRAY; bytearrayParameters.add(parameterValue); } } entity.addPart(PARAMETERS_VALUES, new StringBody(toXML(parametersValues, xstream), UTF8)); int i = 0; for (final Object object : bytearrayParameters) { entity.addPart(BINARY_PARAMETER + i, new ByteArrayBody(serialize(object), BINARY_PARAMETER + i)); i++; } httpEntity = entity; } else { final List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(OPTIONS, toXML(options, xstream))); nvps.add(new BasicNameValuePair(CLASS_NAME_PARAMETERS, toXML(classNameParameters, xstream))); nvps.add(new BasicNameValuePair(PARAMETERS_VALUES, toXML(parametersValues, xstream))); httpEntity = new UrlEncodedFormEntity(nvps, UTF_8); } return httpEntity; }
From source file:org.opendatakit.aggregate.externalservice.REDCapServer.java
public void submitFile(String recordID, String fileField, BlobSubmissionType blob_value, CallingContext cc) throws MalformedURLException, IOException, EntityNotFoundException, ODKDatastoreException { String contentType = blob_value.getContentType(1, cc); String filename = blob_value.getUnrootedFilename(1, cc); filename = fileField + filename.substring(filename.lastIndexOf('.')); /**/*from ww w. ja v a2 s . c om*/ * REDCap server appears to be highly irregular in the structure of the * form-data submission it will accept from the client. The following should * work, but either resets the socket or returns a 403 error. */ MultipartEntity postentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, UTF_CHARSET); FormBodyPart fb; fb = new FormBodyPart("token", new StringBody(getApiKey(), UTF_CHARSET)); postentity.addPart(fb); fb = new FormBodyPart("content", new StringBody("file", UTF_CHARSET)); postentity.addPart(fb); fb = new FormBodyPart("action", new StringBody("import", UTF_CHARSET)); postentity.addPart(fb); fb = new FormBodyPart("record", new StringBody(recordID, UTF_CHARSET)); postentity.addPart(fb); fb = new FormBodyPart("field", new StringBody(fileField, UTF_CHARSET)); postentity.addPart(fb); fb = new FormBodyPart("file", new ByteArrayBody(blob_value.getBlob(1, cc), contentType, filename)); postentity.addPart(fb); submitPost("File import", postentity, null, cc); }
From source file:se.vgregion.service.barium.BariumRestClientImpl.java
/** * Do post multipart./*from www . j a v a 2 s . co m*/ * * @param endpoint the endpoint * @param fileName the file name * @param inputStream the input stream * @return the string * @throws BariumException the barium exception */ String doPostMultipart(String endpoint, String fileName, InputStream inputStream) throws BariumException { DefaultHttpClient httpClient = new DefaultHttpClient(); //httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("140.166.209.205", 8888)); HttpPost httpPost = new HttpPost(this.apiLocation + endpoint); if (ticket != null) { httpPost.setHeader("ticket", ticket); } else { this.connect(); httpPost.setHeader("ticket", ticket); } try { ContentBody contentBody = new InputStreamBody(inputStream, fileName); // Must use HttpMultipartMode.BROWSER_COMPATIBLE in order to use UTF-8 instead of US_ASCII to handle special // characters. MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")) { // Due to a bug in Barium we must not append the charset directive to the content-type header since // nothing is created in Barium if doing so. // todo Try skipping this when we use Barium Live? @Override protected String generateContentType(final String boundary, final Charset charset) { StringBuilder buffer = new StringBuilder(); buffer.append("multipart/form-data; boundary="); buffer.append(boundary); // Comment out this /*if (charset != null) { buffer.append("; charset="); buffer.append(charset.name()); }*/ return buffer.toString(); } }; multipartEntity.addPart("Data", contentBody); httpPost.setEntity(multipartEntity); HttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new BariumException( "Failed to post multipart. Reason: " + response.getStatusLine().getReasonPhrase()); } InputStream content = response.getEntity().getContent(); return toString(content); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (ClientProtocolException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.careerly.utils.HttpClientUtils.java
/** * post???//from w w w . j a v a 2 s. co m * * @param url url * @param fileList * @return */ public static String postFile(String url, List<File> fileList) { HttpPost httppost = new HttpPost(url); String content = null; //1.? MultipartEntity reqEntity = new MultipartEntity(null, null, Consts.UTF_8); for (File tempFile : fileList) { reqEntity.addPart(tempFile.getName(), new FileBody(tempFile)); } httppost.setEntity(reqEntity); try { HttpResponse response = HttpClientUtils.client.execute(httppost); content = EntityUtils.toString(response.getEntity()); } catch (IOException e) { HttpClientUtils.logger.error("postFileForResponse error " + e); } return content; }
From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java
@Override public Promise<Void> addAttachment(final URI attachmentsUri, final InputStream inputStream, final String filename) { final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.defaultCharset()); entity.addPart(FILE_BODY_TYPE, new InputStreamBody(inputStream, filename)); return postAttachments(attachmentsUri, entity); }
From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java
@Override public Promise<Void> addAttachments(final URI attachmentsUri, final AttachmentInput... attachments) { final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.defaultCharset()); for (final AttachmentInput attachmentInput : attachments) { entity.addPart(FILE_BODY_TYPE,// w ww . j av a2 s . com new InputStreamBody(attachmentInput.getInputStream(), attachmentInput.getFilename())); } return postAttachments(attachmentsUri, entity); }
From source file:com.atlassian.jira.rest.client.internal.async.AsynchronousIssueRestClient.java
@Override public Promise<Void> addAttachments(final URI attachmentsUri, final File... files) { final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.defaultCharset()); for (final File file : files) { entity.addPart(FILE_BODY_TYPE, new FileBody(file)); }//from ww w .j a v a 2s . c o m return postAttachments(attachmentsUri, entity); }