List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:nl.esciencecenter.ptk.web.WebClient.java
/** * Perform a managed Http Put with a String as Attachment. *//* w w w . j av a 2s. c o m*/ public int doPutString(String query, String text, StringHolder resultTextH, boolean inbody) throws WebException { HttpPut putMethod = null; URI uri = resolve(query); StringHolder contentTypeH = new StringHolder(); putMethod = new HttpPut(uri.toString()); MultipartEntity multiPart = new MultipartEntity(); StringBody stringB; try { stringB = new StringBody(text); multiPart.addPart("caption", stringB); } catch (UnsupportedEncodingException e) { new WebException(WebException.Reason.IOEXCEPTION, "Unsupported Encoding Exception:" + e.getMessage(), e); } putMethod.setEntity(multiPart); // Method int status = executePut(putMethod, resultTextH, contentTypeH); // Status return this.checkHttpStatus(status, "doPutString():" + query, resultTextH, contentTypeH); }
From source file:immf.ImodeNetClient.java
/** * imode.net????//from w ww . j ava 2s . c om * * @param mail * @return * @throws IOException */ public synchronized void sendMail(SenderMail mail, boolean forcePlaintext) throws IOException, LoginException { if (this.logined == null) { log.warn("i.net????????"); this.logined = Boolean.FALSE; throw new LoginException("imode.net nologin"); } if (this.logined != null && this.logined == Boolean.FALSE) { try { this.login(); } catch (LoginException e) { throw new IOException("Could not login to imode.net"); } } List<String> inlineFileIdList = new LinkedList<String>(); List<String> attachmentFileIdList = new LinkedList<String>(); if (!forcePlaintext) { // html????? for (SenderAttachment file : mail.getInlineFile()) { String docomoFileId = this.sendAttachFile(inlineFileIdList, true, file.getContentTypeWithoutParameter(), file.getFilename(), file.getData()); file.setDocomoFileId(docomoFileId); } } List<SenderAttachment> attachFiles = mail.getAttachmentFile(); for (SenderAttachment file : attachFiles) { // ? this.sendAttachFile(attachmentFileIdList, false, file.getContentTypeWithoutParameter(), file.getFilename(), file.getData()); } // html?? boolean htmlMail = false; String body = null; if (forcePlaintext) { htmlMail = false; body = mail.getPlainBody(); } else { body = mail.getHtmlBody(true); if (body == null) { htmlMail = false; body = mail.getPlainBody(); } else { htmlMail = true; } } // html??????cid? if (htmlMail) { // (???? <img src="40_... ??) body = HtmlConvert.replaceAllCaseInsenstive(body, "<img src=\"cid:[^>]*>", ""); } log.info("Html " + htmlMail); log.info("body " + body); MultipartEntity multi = new MultipartEntity(); try { multi.addPart("folder.id", new StringBody("0", Charset.forName("UTF-8"))); String mailType = null; if (htmlMail) { mailType = "1"; } else { mailType = "0"; } multi.addPart("folder.mail.type", new StringBody(mailType, Charset.forName("UTF-8"))); // ? int recipient = 0; for (InternetAddress ia : mail.getTo()) { multi.addPart("folder.mail.addrinfo(" + recipient + ").mladdr", new StringBody(ia.getAddress(), Charset.forName("UTF-8"))); multi.addPart("folder.mail.addrinfo(" + recipient + ").type", new StringBody("1", Charset.forName("UTF-8"))); recipient++; } for (InternetAddress ia : mail.getCc()) { multi.addPart("folder.mail.addrinfo(" + recipient + ").mladdr", new StringBody(ia.getAddress(), Charset.forName("UTF-8"))); multi.addPart("folder.mail.addrinfo(" + recipient + ").type", new StringBody("2", Charset.forName("UTF-8"))); recipient++; } for (InternetAddress ia : mail.getBcc()) { multi.addPart("folder.mail.addrinfo(" + recipient + ").mladdr", new StringBody(ia.getAddress(), Charset.forName("UTF-8"))); multi.addPart("folder.mail.addrinfo(" + recipient + ").type", new StringBody("3", Charset.forName("UTF-8"))); recipient++; } if (recipient > 5) { throw new IOException("Too Much Recipient"); } // ?? multi.addPart("folder.mail.subject", new StringBody(Util.reverseReplaceUnicodeMapping(mail.getSubject()), Charset.forName("UTF-8"))); // body = Util.reverseReplaceUnicodeMapping(body); // imode.net?? ?10000Bytes? if (body.getBytes().length > 10000) { // ?byte???????????byte?? log.warn("????????10000byte"); throw new IOException("Too Big Message Body. Max 10000 byte."); } multi.addPart("folder.mail.data", new StringBody(body, Charset.forName("UTF-8"))); if (!attachmentFileIdList.isEmpty()) { // for (int i = 0; i < attachmentFileIdList.size(); i++) { multi.addPart("folder.tmpfile(" + i + ").file(0).id", new StringBody(attachmentFileIdList.get(i), Charset.forName("UTF-8"))); } } // ?????? multi.addPart("iemoji(0).id", new StringBody(Character.toString((char) 0xe709), Charset.forName("UTF-8"))); // e709 = UTF-8?ee89c9? multi.addPart("iemoji(1).id", new StringBody(Character.toString((char) 0xe6f0), Charset.forName("UTF-8"))); // e6f0 = UTF-8?ee9bb0? multi.addPart("reqtype", new StringBody("0", Charset.forName("UTF-8"))); HttpPost post = new HttpPost(SendMailUrl); try { addDumyHeader(post); post.setEntity(multi); HttpResponse res = this.executeHttp(post); if (!isJson(res)) { log.warn("?JSON??????"); if (res != null) { // JSON????????????????? log.debug(toStringBody(res)); this.logined = Boolean.FALSE; throw new LoginException("Bad response. no json format."); } else { throw new IOException("imode.net not responding. Try later."); } } JSONObject json = JSONObject.fromObject(toStringBody(res)); String result = json.getJSONObject("common").getString("result"); if (result.equals("PW1409")) { // ???? this.logined = Boolean.FALSE; throw new IOException("PW1409 - session terminated because of your bad mail."); } else if (result.equals("PW1430")) { // ??? throw new IOException("PW1430 - User Unknown."); } else if (result.equals("PW1436")) { // ????? JSONArray jsonaddrs = json.getJSONObject("data").getJSONArray("seaddr"); String addrs = ""; for (int i = 0; i < jsonaddrs.size(); i++) { if (i > 0) { addrs += ", "; } addrs += jsonaddrs.getString(i); } throw new IOException("PW1436 - User Unknown.: " + addrs); } else if (!result.equals("PW1000")) { log.debug(json.toString(2)); throw new IOException("Bad response " + result); } } finally { post.abort(); log.info("??"); } } catch (UnsupportedEncodingException e) { log.fatal(e); } }
From source file:nl.esciencecenter.ptk.web.WebClient.java
/** * Performs a managed HttpPut with a byte array as attachment. Recognized * HTTP Error codes are transformed to Web Exceptions. * //from w w w . j a v a 2 s.c o m * @param query * - relative url to use in HttpPut. * @param bytes * - byes to be uploaded as attachemnt. * @param mimeType * - optional mimeType of content, if null * "application/octet-stream" is used. * @param file * - java File to upload. Must exists * @return filtered Http Status. Common error codes are transformed to * (Web)Exceptions * @throws WebException */ public int doPutBytes(URI uri, byte bytes[], String mimeType, StringHolder resultStrH, PutMonitor optPutMonitor) throws WebException { if (bytes == null) { throw new NullPointerException("Argument by bytes[] is NULL!"); } logger.debugPrintf("doPutBytes() numBytes=%s to:%s\n", bytes.length, uri); if (mimeType == null) { mimeType = "application/octet-stream"; } StringHolder contentTypeH = new StringHolder(); HttpPut putMethod = new HttpPut(uri.toString()); MultipartEntity multiPart = new MultipartEntity(); ByteBufferBody byteBody = new ByteBufferBody(bytes, mimeType, "bytes", optPutMonitor); // Add the part to the MultipartEntity. multiPart.addPart("bytes", byteBody); putMethod.setEntity(multiPart); // Execute Method: int status = executePut(putMethod, resultStrH, contentTypeH); // Status return this.checkHttpStatus(status, "doPutBytes() uri=" + uri, resultStrH, contentTypeH); }
From source file:fm.audiobox.core.models.MediaFile.java
/** * Uploads media file to {@code AudioBox.fm Cloud} drive * //from www . ja va 2 s. com * @param async when {@code true} the upload request will be processed asynchronously * @param uploadHandler the {@link UploadHandler} used to upload file * @param customFields when {@code true} it will upload also {@code title artist album ...} fields * @return the {@link IConnectionMethod} instance used for this upload * @throws ServiceException if any connection error occurrs * @throws LoginException if any login error occurrs */ public IConnectionMethod upload(boolean async, UploadHandler uploadHandler, boolean customFields) throws ServiceException, LoginException, ForbiddenException { String path = IConnector.URI_SEPARATOR.concat(Actions.upload.toString()); MultipartEntity entity = new MultipartEntity(); String mime = MimeTypes.getMime(uploadHandler.getFile()); if (mime == null) { throw new ServiceException("mime type error: file is not supported by AudioBox.fm"); } entity.addPart("files[]", uploadHandler); if (customFields) { List<NameValuePair> fields = this.toQueryParameters(false); for (NameValuePair field : fields) { try { if (field.getValue() != null) { entity.addPart(field.getName(), new StringBody(field.getValue(), "text/plain", Charset.forName("UTF-8"))); } } catch (UnsupportedEncodingException e) { log.warn("Entity " + field.getName() + " cannot be added due to: " + e.getMessage()); } } } if (this.hash != null) { IConnectionMethod request = this.getConnector(IConfiguration.Connectors.NODE).head(this, path, null, null, null); request.addHeader(X_MD5_FILE_HEADER, this.hash); Response r = request.send(false); if (!r.isOK()) { throw new ServiceException(r.getStatus(), r.getBody()); } } IConnectionMethod request = this.getConnector(IConfiguration.Connectors.NODE).post(this, path, null, null); uploadHandler.setRequestMethod(request); request.send(async, entity); return request; }
From source file:immf.ImodeNetClient.java
/** * ????/* ww w . j a va2 s . c o m*/ * * @param fileIdList * @param contentType * @param filename * @param data */ private synchronized String sendAttachFile(List<String> fileIdList, boolean isInline, String contentType, String filename, byte[] data) throws IOException { MultipartEntity multi = new MultipartEntity(); int i = 0; for (Iterator<String> iterator = fileIdList.iterator(); iterator.hasNext(); i++) { String fileId = (String) iterator.next(); try { multi.addPart("tmpfile(" + i + ").id", new StringBody(fileId, Charset.forName("UTF-8"))); } catch (Exception e) { log.error("sendAttachFile (" + i + ")", e); } } multi.addPart("stmpfile.data", new ByteArrayBody(data, contentType, filename)); String url = null; if (isInline) { url = ImgupUrl; } else { url = FileupUrl; } HttpPost post = new HttpPost(url + "?pwsp=" + this.getPwspQuery()); try { addDumyHeader(post); post.setEntity(multi); HttpResponse res = this.executeHttp(post); if (res.getStatusLine().getStatusCode() != 200) { log.warn("attachefile error. " + filename + "/" + res.getStatusLine().getStatusCode() + "/" + res.getStatusLine().getReasonPhrase()); throw new IOException(filename + " error. " + res.getStatusLine().getStatusCode() + "/" + res.getStatusLine().getReasonPhrase()); } if (!isJson(res)) { log.warn("Fileupload??JSON??????"); if (res != null) log.debug(toStringBody(res)); throw new IOException("Bad attached file"); } JSONObject json = JSONObject.fromObject(toStringBody(res)); String result = json.getJSONObject("common").getString("result"); if (!result.equals("PW1000")) { log.debug(json.toString(2)); throw new IOException("Bad fileupload[" + filename + "] response " + result); } // ?ID? String objName = null; if (isInline) { objName = "listPcimg"; } else { objName = "file"; } String fileId = json.getJSONObject("data").getJSONObject(objName).getString("id"); fileIdList.add(fileId); return fileId; } finally { post.abort(); } }
From source file:org.cloudifysource.restclient.GSRestClient.java
/** * This methods executes HTTP post over REST on the given (relative) URL with the given file and properties (also * sent as a separate file).//from ww w. ja va 2 s.co m * * @param relativeUrl * The URL to post to. * @param additionalFiles * The files to send (example: <SOME PATH>/tomcat.zip). * @param props * The properties of this POST action (example: com.gs.service.type=WEB_SERVER) * @param params * as a map of names and values. * @return The response object from the REST server * @throws RestException * Reporting failure to post the file. */ public final Object postFiles(final String relativeUrl, final Properties props, final Map<String, String> params, final Map<String, File> additionalFiles) throws RestException { final MultipartEntity reqEntity = new MultipartEntity(); // It should be possible to dump the properties into a String entity, // but I can't get it to work. So using a temp file instead. // Idiotic, but works. // dump map into file File tempFile; try { tempFile = writeMapToFile(props); } catch (final IOException e) { throw new RestException(e); } final FileBody propsFile = new FileBody(tempFile); reqEntity.addPart("props", propsFile); if (params != null) { try { for (Map.Entry<String, String> param : params.entrySet()) { reqEntity.addPart(param.getKey(), new StringBody(param.getValue(), Charset.forName("UTF-8"))); } } catch (final IOException e) { throw new RestException(e); } } // add the rest of the files for (Entry<String, File> entry : additionalFiles.entrySet()) { final File file = entry.getValue(); if (file != null) { final FileBody bin = new FileBody(file); reqEntity.addPart(entry.getKey(), bin); } } final HttpPost httppost = new HttpPost(getFullUrl(relativeUrl)); httppost.setEntity(reqEntity); return executeHttpMethod(httppost); }
From source file:com.parworks.androidlibrary.ar.ARSiteImpl.java
private MultipartEntity getEntityFromVertices(List<Vertex> vertices) { MultipartEntity entity = new MultipartEntity(); for (Vertex currentVertex : vertices) { try {// ww w.j a v a2 s.c o m entity.addPart("v", new StringBody((int) currentVertex.getxCoord() + "," + (int) currentVertex.getyCoord())); } catch (UnsupportedEncodingException e) { throw new ARException(e); } } return entity; }