private void setupMultipartEntity(HttpPost httpPost){ if(isDebug){ log("Request upload file:"+mFile.getName() +" exists:"+ mFile.exists()); } MultipartEntityBuilder entity = MultipartEntityBuilder.create() .seContentType(ContentType.MULTIPART_FORM_DATA) .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody(mName,mFile,ContentType.DEFAULT_BINARY,mFileName) //uploadFile对应服务端类的同名属性<File类型> .setCharset(DEFAULT_CHARSET); for (String key:mFileParames.keySet()) { String value = mFileParames.get(key); entity.addTextBody(key,value); } httpPost.setEntity(entity.build()); }
/** * * @param param * apikey sign * @param layout * {@code VideoLayout} * @param material * 视频资料zip文件 * * @return */ public Result<Template> addTpl(Map<String, String> param, String layout, byte[] material) { Result<Template> r = new Result<>(); if (layout == null || material == null) return r.setCode(Code.ARGUMENT_MISSING); List<NameValuePair> list = param2pair(param, r, APIKEY, SIGN); if (r.getCode() != Code.OK) return r; Charset ch = Charset.forName(charset()); MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(ch).setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (NameValuePair pair : list) { builder.addTextBody(pair.getName(), pair.getValue(), ContentType.create("text/plain", ch)); } builder.addTextBody(LAYOUT, layout, ContentType.APPLICATION_JSON); builder.addBinaryBody(MATERIAL, material, ContentType.create("application/octet-stream", ch), null); StdResultHandler<Template> h = new StdResultHandler<>(); try { return path("add_tpl.json").post(new HttpEntityWrapper(builder.build()), h, r); } catch (Exception e) { return h.catchExceptoin(e, r); } }
@Override public WxMediaUploadResult execute(String uri, File file) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpPost.setConfig(config); } if (file != null) { HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", file) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); } try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return WxMediaUploadResult.fromJson(responseContent); } finally { httpPost.releaseConnection(); } }
/** * Adds a stream to an HTTP entity * * @param someStream Input stream to be added to an HTTP entity * @param fieldName A description of the entity content * @param fileName Name of the file attached as an entity * @return HTTP entity * @throws IOException Signals a failure while reading the input stream */ HttpEntity addStreamToEntity(InputStream someStream, String fieldName, String fileName) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int bytesRead; byte[] bytes = new byte[1024]; while ((bytesRead = someStream.read(bytes)) > 0) { byteArrayOutputStream.write(bytes, 0, bytesRead); } byte[] data = byteArrayOutputStream.toByteArray(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.setStrictMode(); builder.addBinaryBody(fieldName, data, ContentType.MULTIPART_FORM_DATA, fileName); return builder.build(); }
private HttpPost postForm(String url, Map<String, String> params, Map<String, File> files, String charset) { if (StringUtils.isBlank(charset)) { charset = "UTF-8"; } HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (null != params) { Set<String> keySet = params.keySet(); for (String key : keySet) { builder.addTextBody(key, params.get(key), ContentType.create("text/plain", Charset.forName(charset))); } } if (CollectionUtils.isBlank(files)) { for (String filename : files.keySet()) { builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody(filename, files.get(filename), ContentType.DEFAULT_BINARY, filename); } } httpPost.setEntity(builder.build()); return httpPost; }
private HttpPost composeMultiPartFormRequest(final String uri, final Parameters parameters, final Map<String, ContentBody> files) { HttpPost request = new HttpPost(uri); MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { Charset utf8 = Charset.forName("UTF-8"); for(Parameter param : parameters) if(param.isSingleValue()) multiPartEntity.addPart(param.getName(), new StringBody(param.getValue(), utf8)); else for(String value : param.getValues()) multiPartEntity.addPart(param.getName(), new StringBody(value, utf8)); } catch (UnsupportedEncodingException e) { throw MechanizeExceptionFactory.newException(e); } List<String> fileNames = new ArrayList<String>(files.keySet()); Collections.sort(fileNames); for(String name : fileNames) { ContentBody contentBody = files.get(name); multiPartEntity.addPart(name, contentBody); } request.setEntity(multiPartEntity); return request; }
public HttpPost initRequest(final FileUploadParameter parameter) { final FileUploadAddress fileUploadAddress = getDependResult(FileUploadAddress.class); final HttpPost request = new HttpPost("http://" + fileUploadAddress.getData().getUp() + CONST.URI_PATH); final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setCharset(Consts.UTF_8); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart(CONST.QID_NAME, new StringBody(getLoginInfo().getQid(), ContentType.DEFAULT_BINARY)); multipartEntity.addPart("ofmt", new StringBody("json", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("method", new StringBody("Upload.web", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("token", new StringBody(readCookieStoreValue("token"), ContentType.DEFAULT_BINARY)); multipartEntity.addPart("v", new StringBody("1.0.1", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("tk", new StringBody(fileUploadAddress.getData().getTk(), ContentType.DEFAULT_BINARY)); multipartEntity.addPart("Upload", new StringBody("Submit Query", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("devtype", new StringBody("web", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("pid", new StringBody("ajax", ContentType.DEFAULT_BINARY)); multipartEntity.addPart("Filename", new StringBody(parameter.getUploadFile().getName(), ContentType.APPLICATION_JSON)); multipartEntity.addPart("path", new StringBody(parameter.getPath(), ContentType.APPLICATION_JSON));// 解决中文不识别问题 multipartEntity.addBinaryBody("file", parameter.getUploadFile()); request.setEntity(multipartEntity.build()); return request; }
public static void main(String args[]){ HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8080/sso-web/upload"); httpPost.addHeader("Range","bytes=10000-"); final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setCharset(Consts.UTF_8); multipartEntity.setMode(HttpMultipartMode.STRICT); multipartEntity.addBinaryBody("file", new File("/Users/huanghuanlai/Desktop/test.java")); httpPost.setEntity(multipartEntity.build()); try { HttpResponse response = httpClient.execute(httpPost); } catch (IOException e) { e.printStackTrace(); } }
public void submitFile(String recordID, String fileField, BlobSubmissionType blob_value, CallingContext cc) throws MalformedURLException, IOException, ODKDatastoreException { String contentType = blob_value.getContentType(1, cc); String filename = blob_value.getUnrootedFilename(1, cc); filename = fileField + filename.substring(filename.lastIndexOf('.')); /** * 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. */ ContentType utf8Text = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), UTF_CHARSET); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .setCharset(UTF_CHARSET); builder.addTextBody("token", getApiKey(), utf8Text) .addTextBody("content", "file", utf8Text) .addTextBody("action", "import", utf8Text) .addTextBody("record", recordID, utf8Text) .addTextBody("field", fileField, utf8Text) .addBinaryBody("file", blob_value.getBlob(1, cc), ContentType.create(contentType), filename); submitPost("File import", builder.build(), null, cc); }
private void fileUpload() throws Exception { httpPost = new NUHttpPost(postURL); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("notprivate", new StringBody("false")); mpEntity.addPart("folder", new StringBody("/")); mpEntity.addPart("Filedata", createMonitoredFileBody()); httpPost.setHeader("Cookie", usercookie); httpPost.setEntity(mpEntity); uploading(); NULogger.getLogger().info("Now uploading your file into zippyshare.com"); httpResponse = httpclient.execute(httpPost); gettingLink(); HttpEntity resEntity = httpResponse.getEntity(); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); downloadlink = StringUtils.stringBetweenTwoStrings(uploadresponse, "value=\"http://", "\""); downloadlink = "http://" + downloadlink; NULogger.getLogger().log(Level.INFO, "Download Link : {0}", downloadlink); downURL=downloadlink; }else{ throw new Exception("ZippyShare server problem or Internet connectivity problem"); } }
public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file, Map<String, String> mStringPart) { super(Method.POST, url, errorListener); this.mListener = listener; this.mFilePart = file; this.mStringPart = mStringPart; entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); try { entity.setCharset(CharsetUtils.get("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } buildMultipartEntity(); httpentity = entity.build(); }
private static void fileUpload() throws Exception { file = new File("C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample Pictures\\Sunset.jpg"); httpclient = new DefaultHttpClient(); //http://upload3.divshare.com/cgi-bin/upload.cgi?sid=8ef15852c69579ebb2db1175ce065ba6 HttpPost httppost = new HttpPost(downURL + "cgi-bin/upload.cgi?sid=" + sid); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("file[0]", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into divshare.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(resEntity)); }
/** * Handles conversion from file to file with given File object * @param dest The output file object * @return True on success, false on error * @throws IOException */ private boolean convertFromFileToFile(File dest) throws IOException { if (!this.getInputFile().exists()) { throw new IllegalArgumentException("MsWordToImageConvert: Input file was not found at '" + this.input.getValue() + "'"); } HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(this.constructMsWordToImageAddress(new HashMap<>())); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("file_contents", new FileBody(this.getInputFile())); post.setEntity(builder.build()); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); try (FileOutputStream fileOS = new FileOutputStream(dest)) { entity.writeTo(fileOS); fileOS.flush(); } return true; }
private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:/install.txt"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into sharesend.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("Upload Response : " + uploadresponse); System.out.println("Download Link : http://sharesend.com/" + uploadresponse); httpclient.getConnectionManager().shutdown(); }
public static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); //reqEntity.addPart("string_field",new StringBody("field value")); FileBody bin = new FileBody(new File("/home/vigneshwaran/VIGNESH/naruto.txt")); reqEntity.addPart("fff", bin); httppost.setEntity(reqEntity); System.out.println("Now uploading your file into 2shared.com. Please wait......................"); HttpResponse response = httpclient.execute(httppost); // HttpEntity resEntity = response.getEntity(); // // if (resEntity != null) { // String page = EntityUtils.toString(resEntity); // System.out.println("PAGE :" + page); // } }
private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); //httppost.setHeader("Cookie", sidcookie+";"+mysessioncookie); file = new File("h:/UploadingdotcomUploaderPlugin.java"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("notprivate", new StringBody("false")); mpEntity.addPart("folder", new StringBody("/")); mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into zippyshare.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } downloadlink=parseResponse(uploadresponse, "value=\"http://", "\""); downloadlink="http://"+downloadlink; System.out.println("Download Link : "+downloadlink); httpclient.getConnectionManager().shutdown(); }
private void uploadMixtureCloud() throws Exception { uploadInitialising(); responseString = NUHttpClientUtils.getData("https://www.mixturecloud.com/files", httpContext); uploadUrl = "http:" + StringUtils.stringBetweenTwoStrings(responseString, "urlUpload : '", "',"); NULogger.getLogger().log(Level.INFO, "uploadUrl is {0}", uploadUrl); httpPost = new NUHttpPost(uploadUrl); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("cmd", new StringBody("upload")); mpEntity.addPart("target", new StringBody("mcm1_MA")); mpEntity.addPart("upload[]", createMonitoredFileBody()); httpPost.setEntity(mpEntity); uploading(); httpResponse = httpclient.execute(httpPost, httpContext); HttpEntity resEntity = httpResponse.getEntity(); responseString = EntityUtils.toString(resEntity); //NULogger.getLogger().log(Level.INFO, "stringResponse : {0}", responseString); JSONObject jSonObject = new JSONObject(responseString); String webAccess = jSonObject.getJSONArray("file_data").getJSONObject(0).getString("web_access"); downloadUrl += webAccess; downURL = downloadUrl; }
/** * POST request * @param urlstring * @param map * @param useAuthentication * @throws ClientProtocolException * @throws IOException */ public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication) throws ClientProtocolException, IOException { this.request = new HttpPost(urlstring); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (Map.Entry<String, byte[]> entry: map.entrySet()) { entityBuilder.addBinaryBody(entry.getKey(), entry.getValue()); } ((HttpPost) this.request).setEntity(entityBuilder.build()); this.request.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent); this.init(); }
public static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //如果有SocketTimeoutException等情况,可修改这个枚举 //builder.setCharset(Charset.forName("UTF-8")); //不要用这个,会导致服务端接收不到参数 if (params != null && params.size() > 0) { for (NameValuePair p : params) { builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8")); } } if (files != null && files.size() > 0) { Set<Entry<String, File>> entries = files.entrySet(); for (Entry<String, File> entry : entries) { builder.addPart(entry.getKey(), new FileBody(entry.getValue())); } } return builder.build(); }
/** * Create Post Request with FormBodyPart body */ public HttpPost createPost(String uri, LinkedList<FormBodyPart> partsList) { HttpPost postRequest = new HttpPost(uri); MultipartEntity multipartRequest = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (FormBodyPart part : partsList) { multipartRequest.addPart(part); } postRequest.setEntity(multipartRequest); return postRequest; }
/** * * Send POST request to DLMS back end with the result file * @param bluemixToken - the Bluemix token * @param contents - the result file * @param jobUrl - the build url of the build job in Jenkins * @param timestamp * @return - response/error message from DLMS */ public String sendFormToDLMS(String bluemixToken, FilePath contents, String lifecycleStage, String jobUrl, String timestamp) throws IOException { // create http client and post method CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(this.dlmsUrl); postMethod = addProxyInformation(postMethod); // build up multi-part forms MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); if (contents != null) { File file = new File(root, contents.getName()); FileBody fileBody = new FileBody(file); builder.addPart("contents", fileBody); builder.addTextBody("test_artifact", file.getName()); if (this.isDeploy) { builder.addTextBody("environment_name", environmentName); } //Todo check the value of lifecycleStage builder.addTextBody("lifecycle_stage", lifecycleStage); builder.addTextBody("url", jobUrl); builder.addTextBody("timestamp", timestamp); String fileExt = FilenameUtils.getExtension(contents.getName()); String contentType; switch (fileExt) { case "json": contentType = CONTENT_TYPE_JSON; break; case "xml": contentType = CONTENT_TYPE_XML; break; default: return "Error: " + contents.getName() + " is an invalid result file type"; } builder.addTextBody("contents_type", contentType); HttpEntity entity = builder.build(); postMethod.setEntity(entity); postMethod.setHeader("Authorization", bluemixToken); } else { return "Error: File is null"; } CloseableHttpResponse response = null; try { response = httpClient.execute(postMethod); // parse the response json body to display detailed info String resStr = EntityUtils.toString(response.getEntity()); JsonParser parser = new JsonParser(); JsonElement element = parser.parse(resStr); if (!element.isJsonObject()) { // 401 Forbidden return "Error: Upload is Forbidden, please check your org name. Error message: " + element.toString(); } else { JsonObject resJson = element.getAsJsonObject(); if (resJson != null && resJson.has("status")) { return String.valueOf(response.getStatusLine()) + "\n" + resJson.get("status"); } else { // other cases return String.valueOf(response.getStatusLine()); } } } catch (IOException e) { e.printStackTrace(); throw e; } }
@Override public void postFileUpload(final String uploadServletUrl, final String fileName, final byte[] bytes) throws IOException { File file = null; try { client = new DefaultHttpClient(); client.getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // if uploadServletURL is malformed - exception is thrown new URL(uploadServletUrl); file = File.createTempFile(fileName, ""); final BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file)); bos.write(bytes); bos.flush(); bos.close(); final HttpPost post = new HttpPost(uploadServletUrl); final MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("file", new FileBody(file, "application/octet-stream")); post.setEntity(entity); client.execute(post); } catch (final IOException e) { throw e; } finally { client.getConnectionManager().shutdown(); if (file != null && file.exists()) { file.delete(); } } }
@Override public WxMediaImgUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File data) throws WxErrorException, IOException { if (data == null) { throw new WxErrorException(WxError.newBuilder().setErrorMsg("文件对象为空").build()); } HttpPost httpPost = new HttpPost(uri); if (httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); httpPost.setConfig(config); } HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", data) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); try (CloseableHttpResponse response = httpclient.execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return WxMediaImgUploadResult.fromJson(responseContent); } }
@Override public WxMediaUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File file) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); httpPost.setConfig(config); } if (file != null) { HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", file) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); } try (CloseableHttpResponse response = httpclient.execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return WxMediaUploadResult.fromJson(responseContent); } finally { httpPost.releaseConnection(); } }
@Override public String uploadFile(String systemName, String entityName, String apiUrl, List<File> fileList, String requestParamInputName) throws IllegalStateException { HttpResponse response = null; HttpPost httpPost = getHttpPost(); try { List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>(); String[] urlAndParame = apiUrl.split("\\?"); String apiUrlNoParame = urlAndParame[0]; Map<String, String> parameMap = StrUtil.splitUrlToParameMap(apiUrl); Iterator<String> parameIterator = parameMap.keySet().iterator(); httpPost.setURI(new URI(apiUrlNoParame)); MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); while (parameIterator.hasNext()) { String parameName = parameIterator.next(); nvps.add(new BasicNameValuePair(parameName, parameMap.get(parameName))); multipartEntity.addPart(parameName, new StringBody(parameMap.get(parameName), ContentType.create("text/plain", Consts.UTF_8))); } if (!StrUtil.isBlank(systemName)) { multipartEntity.addPart("systemName", new StringBody(systemName, ContentType.create("text/plain", Consts.UTF_8))); } if (!StrUtil.isBlank(entityName)) { multipartEntity.addPart("entityName", new StringBody(entityName, ContentType.create("text/plain", Consts.UTF_8))); } // 多文件上传 获取文件数组前台标签name值 if (!StrUtil.isBlank(requestParamInputName)) { multipartEntity.addPart("filesName", new StringBody(requestParamInputName, ContentType.create("text/plain", Consts.UTF_8))); } if (fileList != null) { for (int i = 0, size = fileList.size(); i < size; i++) { File file = fileList.get(i); multipartEntity.addBinaryBody(requestParamInputName, file, ContentType.DEFAULT_BINARY, file.getName()); } } HttpEntity entity = multipartEntity.build(); httpPost.setEntity(entity); response = httpClient.execute(httpPost); String statusCode = String.valueOf(response.getStatusLine().getStatusCode()); if (statusCode.indexOf("20") == 0) { entity = response.getEntity(); // String contentType = entity.getContentType().getValue();// // application/json;charset=ISO-8859-1 return StrUtil.readStream(entity.getContent(), responseContextEncode); } else { LOG.error("返回状态码:[" + statusCode + "]"); return "返回状态码:[" + statusCode + "]"; } } catch (Exception e) { e.printStackTrace(); } finally { httpPost.releaseConnection(); } return null; }
private static HttpMultipartMode adaptMultipartMode(MultipartMode mode) { switch (mode) { case STRICT: return HttpMultipartMode.STRICT; case BROWSER_COMPATIBLE: return HttpMultipartMode.BROWSER_COMPATIBLE; case RFC6532: return HttpMultipartMode.RFC6532; default: throw new IllegalArgumentException("Unknown multipart mode: " + mode); } }
public ApiResponse uploadWelcomeMessage(String filePath, int messageId, int selectedMessageId) { File file = new File(filePath); HttpPost uploadRequest = new HttpPost(WELCOME_MESSAGE_URI); StringBody commandeBody = new StringBody("annonce_mess", ContentType.MULTIPART_FORM_DATA); StringBody messageIdBody = new StringBody(String.valueOf(messageId), ContentType.MULTIPART_FORM_DATA); StringBody maxFileSizeBody = new StringBody("5242880", ContentType.MULTIPART_FORM_DATA); StringBody selectMessageBody = new StringBody(String.valueOf(selectedMessageId), ContentType.MULTIPART_FORM_DATA); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("FILE", file, ContentType.create("audio/mp3"), "message.mp3"); builder.addPart("commande", commandeBody); builder.addPart("id_message", messageIdBody); builder.addPart("id_message_select", selectMessageBody); builder.addPart("MAX_FILE_SIZE", maxFileSizeBody); HttpEntity entity = builder.build(); uploadRequest.setEntity(entity); HttpResponse response = executeRequest(uploadRequest); return new ApiResponse(HttpStatus.gethttpStatus(response.getStatusLine().getStatusCode())); }
private HttpPost buildHttpPost(String fileNameWithPath, String product) { HttpPost httpPost = new HttpPost(LogUtil.getInstance().getLogUrl()); MultipartEntity mutiEntity = new MultipartEntity(HttpMultipartMode.STRICT); httpPost.setEntity(mutiEntity); File file = new File(fileNameWithPath); try { mutiEntity.addPart("LogFileInfo", new StringBody("{\"product\":\"" + product + "\"}", Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "UTF-8 is not supported encode"); //LOGGER.error("UTF-8 is not supported encode"); } mutiEntity.addPart("LogFile", new FileBody(file)); return httpPost; }
private String sendFile(String chat_id, File file, String type, String caption, boolean disable_notification, int reply_to_message_id, ReplyMarkup reply_markup, int duration, String performer, String title, int width, int height) throws IOException { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("chat_id", new StringBody(chat_id, ContentType.DEFAULT_TEXT)); if (caption != null) builder.addPart("caption", new StringBody(caption, ContentType.DEFAULT_TEXT)); if (disable_notification != false) builder.addPart("disable_notification", new StringBody(Boolean.toString(disable_notification), ContentType.DEFAULT_TEXT)); if (reply_to_message_id > 0) builder.addPart("reply_to_message_id", new StringBody(Integer.toString(reply_to_message_id), ContentType.DEFAULT_TEXT)); if (reply_markup != null) builder.addPart("reply_markup", new StringBody(URLEncoder.encode(reply_markup.toJSONString(), "utf-8"), ContentType.DEFAULT_TEXT)); if (duration > 0) builder.addPart("duration", new StringBody(Integer.toString(duration), ContentType.DEFAULT_TEXT)); if (performer != null) builder.addPart("performer", new StringBody(performer, ContentType.DEFAULT_TEXT)); if (title != null) builder.addPart("title", new StringBody(title, ContentType.DEFAULT_TEXT)); if (width > 0) builder.addPart("width", new StringBody(Integer.toString(width), ContentType.DEFAULT_TEXT)); if (height > 0) builder.addPart("height", new StringBody(Integer.toString(height), ContentType.DEFAULT_TEXT)); builder.addPart(type, new FileBody(file, ContentType.DEFAULT_BINARY)); HttpEntity entity = builder.build(); HttpPost post = new HttpPost(url + "/send" + type); post.setEntity(entity); CloseableHttpClient httpclient = HttpClients.createMinimal(); HttpResponse response = httpclient.execute(post); return response.toString(); }
private String sendFile(String chat_id, String file_id, String type, String caption, boolean disable_notification, int reply_to_message_id, ReplyMarkup reply_markup, int duration, String performer, String title, int width, int height) throws IOException { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("chat_id", new StringBody(chat_id, ContentType.DEFAULT_TEXT)); if (caption != null) builder.addPart("caption", new StringBody(caption, ContentType.DEFAULT_TEXT)); if (disable_notification != false) builder.addPart("disable_notification", new StringBody(Boolean.toString(disable_notification), ContentType.DEFAULT_TEXT)); if (reply_to_message_id > 0) builder.addPart("reply_to_message_id", new StringBody(Integer.toString(reply_to_message_id), ContentType.DEFAULT_TEXT)); if (reply_markup != null) builder.addPart("reply_markup", new StringBody(URLEncoder.encode(reply_markup.toJSONString(), "utf-8"), ContentType.DEFAULT_TEXT)); if (duration > 0) builder.addPart("duration", new StringBody(Integer.toString(duration), ContentType.DEFAULT_TEXT)); if (performer != null) builder.addPart("performer", new StringBody(performer, ContentType.DEFAULT_TEXT)); if (title != null) builder.addPart("title", new StringBody(title, ContentType.DEFAULT_TEXT)); if (width > 0) builder.addPart("width", new StringBody(Integer.toString(width), ContentType.DEFAULT_TEXT)); if (height > 0) builder.addPart("height", new StringBody(Integer.toString(height), ContentType.DEFAULT_TEXT)); builder.addPart(type, new StringBody(file_id, ContentType.DEFAULT_TEXT)); HttpEntity entity = builder.build(); HttpPost post = new HttpPost(url + "/send" + type); post.setEntity(entity); CloseableHttpClient httpclient = HttpClients.createMinimal(); HttpResponse response = httpclient.execute(post); return response.toString(); }
@Override public WxMediaImgUploadResult execute(String uri, File data) throws WxErrorException, IOException { if (data == null) { throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("文件对象为空").build()); } HttpPost httpPost = new HttpPost(uri); if (requestHttp.getRequestHttpProxy() != null) { RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); httpPost.setConfig(config); } HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", data) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return WxMediaImgUploadResult.fromJson(responseContent); } }
public String importImage(File file) throws IOException { if(getGalleryId() != null) { String url = getImportImageUrl(); HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get, context); this.cookies = response.getFirstHeader(Constant.SET_COOKIE_HEADER).getValue(); // load file in form FileBody cbFile = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("physical", cbFile); builder.addPart("title", new StringBody("Image importée via ZestWriter", Charset.forName("UTF-8"))); builder.addPart(Constant.CSRF_ZDS_KEY, new StringBody(getCookieValue(cookieStore, Constant.CSRF_COOKIE_KEY), ContentType.MULTIPART_FORM_DATA)); Pair<Integer, String> resultPost = sendPost(url, builder.build()); Document doc = Jsoup.parse(resultPost.getValue()); Elements endPoints = doc.select("input[name=avatar_url]"); if(!endPoints.isEmpty()) { return getBaseUrl() + endPoints.first().attr("value").trim(); } } return "http://"; }
private boolean uploadContent(String filePath, String url, String msg) throws IOException{ HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get, context); this.cookies = response.getFirstHeader(Constant.SET_COOKIE_HEADER).getValue(); // load file in form FileBody cbFile = new FileBody(new File(filePath)); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("archive", cbFile); builder.addPart("subcategory", new StringBody("115", ContentType.MULTIPART_FORM_DATA)); builder.addPart("msg_commit", new StringBody(msg, Charset.forName("UTF-8"))); builder.addPart(Constant.CSRF_ZDS_KEY, new StringBody(getCookieValue(cookieStore, Constant.CSRF_COOKIE_KEY), ContentType.MULTIPART_FORM_DATA)); Pair<Integer, String> resultPost = sendPost(url, builder.build()); int statusCode = resultPost.getKey(); switch (statusCode) { case 200: return !resultPost.getValue ().contains ("alert-box alert"); case 404: log.debug("L'id cible du contenu ou le slug est incorrect. Donnez de meilleur informations"); return false; case 403: log.debug("Vous n'êtes pas autorisé à uploader ce contenu. Vérifiez que vous êtes connecté"); return false; case 413: log.debug("Le fichier que vous essayer d'envoyer est beaucoup trop lourd. Le serveur n'arrive pas à le supporter"); return false; default: log.debug("Problème d'upload du contenu. Le code http de retour est le suivant : "+statusCode); return false; } }
@Deprecated public static String uploadFileFromPath(String requestUrl, String requestMethod, String filePath) throws ClientProtocolException, IOException{ String result = null; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(requestUrl); // 把文件转换成流对象FileBody File file = new File(filePath); FileBody media = new FileBody(file); /*StringBody uploadFileName = new StringBody("my.png", ContentType.create("text/plain", Consts.UTF_8));*/ // 以浏览器兼容模式运行,防止文件名乱码。 HttpEntity reqEntity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart("file", media) // media对应服务端类的同名属性<File类型> .setCharset(CharsetUtils.get("UTF-8")).build(); httpPost.setEntity(reqEntity); // 发起请求 并返回请求的响应 CloseableHttpResponse response = httpClient.execute(httpPost); try { // 获取响应对象 HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, Charset.forName("UTF-8")); } // 销毁 EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpClient.close(); } return result; }
public WebResponse uploadFile(String path, String fname, InputStream in, String stoken) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(path); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA); builder.addPart("fname", fn); builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname); BasicCookieStore cookieStore = new BasicCookieStore(); if (stoken != null) { BasicClientCookie cookie = new BasicClientCookie( Constants.SECURE_TOKEN_NAME, stoken); cookie.setDomain(TestConstants.JETTY_HOST); cookie.setPath("/"); cookieStore.addCookie(cookie); } TestConstants.LOG.debug("stoken=" + stoken); HttpClient client = HttpClientBuilder.create(). setDefaultCookieStore(cookieStore).build(); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse response = client.execute(post); String body; ResponseHandler<String> handler = new BasicResponseHandler(); try { body = handler.handleResponse(response); } catch (HttpResponseException e) { return new WebResponse(e.getStatusCode(), e.getMessage()); } return new WebResponse(response.getStatusLine().getStatusCode(), body); }
private HttpPost buildHttpPost(String fileNameWithPath, String product) { HttpPost httpPost = new HttpPost(serverUrl); MultipartEntity mutiEntity = new MultipartEntity(HttpMultipartMode.STRICT); httpPost.setEntity(mutiEntity); File file = new File(fileNameWithPath); try { mutiEntity.addPart("LogFileInfo", new StringBody("{\"product\":\"" + product + "\"}", Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { logUtil.showRunningtLog(LOG_TYPE_E.LOG_ERROR, "LogFileUploadTask.buildHttpPost()", "UTF-8 is not supported encode"); } mutiEntity.addPart("LogFile", new FileBody(file)); return httpPost; }
private HttpResponse sendData(File data, String urlStr) throws IOException{ CloseableHttpClient client = burpExtender.getHttpClient(); if(client == null) return null; HttpPost post = new HttpPost(urlStr); post.setHeader("API-Key", burpExtender.getApiKey()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("file", new FileBody(data)); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { EntityUtils.consume(resEntity); } client.close(); return response; }
@Override public WxMediaImgUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File data) throws WxErrorException, IOException { if (data == null) { throw new WxErrorException(WxError.newBuilder().setErrorMsg("文件对象为空").build()); } HttpPost httpPost = new HttpPost(uri); if (httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); httpPost.setConfig(config); } HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", data) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); CloseableHttpResponse response = httpclient.execute(httpPost); try { String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return WxMediaImgUploadResult.fromJson(responseContent); } finally { IOUtils.closeQuietly(response); } }
@Override public WxMediaUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File file) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); httpPost.setConfig(config); } if (file != null) { HttpEntity entity = MultipartEntityBuilder .create() .addBinaryBody("media", file) .setMode(HttpMultipartMode.RFC6532) .build(); httpPost.setEntity(entity); httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); } CloseableHttpResponse response = null; try { response = httpclient.execute(httpPost); String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); WxError error = WxError.fromJson(responseContent); if (error.getErrorCode() != 0) { throw new WxErrorException(error); } return WxMediaUploadResult.fromJson(responseContent); } finally { IOUtils.closeQuietly(response); httpPost.releaseConnection(); } }
public static MultipartEntity getMultipartEntity(List<FormBodyPart> formBodyParts) { MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8)); for (FormBodyPart formBodyPart : formBodyParts) { DebugLog.d(TAG, formBodyPart.getHeader().toString()); multipartEntity.addPart(formBodyPart); } return multipartEntity; }