private static int postData(String url, byte[] encryptedBytes, byte[] encryptedSecretKey, byte[] signature, String serviceName) throws IOException { MultipartEntity multipartEntity = new MultipartEntity(); String filename=serviceName+'_'+System.currentTimeMillis()+".hl7"; multipartEntity.addPart("importFile", new ByteArrayBody(encryptedBytes, filename)); multipartEntity.addPart("key", new StringBody(new String(Base64.encodeBase64(encryptedSecretKey), MiscUtils.DEFAULT_UTF8_ENCODING))); multipartEntity.addPart("signature", new StringBody(new String(Base64.encodeBase64(signature), MiscUtils.DEFAULT_UTF8_ENCODING))); multipartEntity.addPart("service", new StringBody(serviceName)); multipartEntity.addPart("use_http_response_code", new StringBody("true")); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(multipartEntity); HttpClient httpClient = getTrustAllHttpClient(); httpClient.getParams().setParameter("http.connection.timeout", CONNECTION_TIME_OUT); HttpResponse httpResponse = httpClient.execute(httpPost); int statusCode=httpResponse.getStatusLine().getStatusCode(); logger.debug("StatusCode:" + statusCode); return (statusCode); }
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 int put2(byte[] data) throws Exception { log.debug("Put " + URL.getPath()); HttpPut httpPut = new HttpPut(URL.getPath()); if (isAuthByPrivateKey) httpPut.setHeaders(headersArray); log.debug("Put send :" + data.length); // InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data), data.length); // reqEntity.setContentType("binary/octet-stream"); // reqEntity.setChunked(false); // // BufferedHttpEntity myEntity = null; // try { // myEntity = new BufferedHttpEntity(reqEntity); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } MultipartEntity myEntity = new MultipartEntity(); myEntity.addPart("files[]",new ByteArrayBody(data,"toto")) ; //int code = client.post(entity); httpPut.setEntity(myEntity); response = client.execute(targetHost, httpPut, localcontext); return response.getStatusLine().getStatusCode(); }
public void editWikiPage(String[][] currentCommentInformation, String subreddit) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://www.reddit.com/r/"+subreddit+"/api/wiki/edit"); MultipartEntity nvps = new MultipartEntity(); httpPost.addHeader("User-Agent","User-Agent: LGG Bot (by /u/amdphenom"); httpPost.addHeader("Cookie","reddit_session=" + user.getCookie()); nvps.addPart("r", new StringBody(subreddit)); nvps.addPart("uh", new StringBody(user.getModhash())); nvps.addPart("formid", new StringBody("image-upload")); httpPost.setEntity(nvps); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { response2.close(); } }
public void uploadFile(String url, byte[] data) throws CytomineException { try { HttpClient client = null; MultipartEntity entity = new MultipartEntity(); entity.addPart("files[]", new ByteArrayBody(data, new Date().getTime() + "file")); client = new HttpClient(publicKey, privateKey, getHost()); client.authorize("POST", url, entity.getContentType().getValue(), "application/json,*/*"); client.connect(getHost() + url); int code = client.post(entity); String response = client.getResponseData(); log.debug("response=" + response); client.disconnect(); JSONObject json = createJSONResponse(code, response); } catch (IOException e) { throw new CytomineException(e); } }
/** * Create a Credentials file with the provided authentication parameters * * @param login username * @param pass password * @param ssh private ssh key * @return the the Credentials file as a base64 String * @throws RestServerException * @throws ServiceException */ @Override public String createCredentials(String login, String pass, String ssh) throws RestServerException, ServiceException { HttpPost method = new HttpPost(SchedulerConfig.get().getRestUrl() + "/scheduler/createcredential"); try { MultipartEntity entity = createLoginPasswordSSHKeyMultipart(login, pass, ssh); method.setEntity(entity); HttpResponse response = httpClient.execute(method); String responseAsString = convertToString(response.getEntity().getContent()); switch (response.getStatusLine().getStatusCode()) { case 200: return responseAsString; default: throw new RestServerException(response.getStatusLine().getStatusCode(), responseAsString); } } catch (IOException e) { throw new ServiceException(e.getMessage()); } finally { method.releaseConnection(); } }
/** * Create a Credentials file with the provided authentication parameters * * @param login username * @param pass password * @param ssh private ssh key * @return the the Credentials file as a base64 String * @throws ServiceException */ public String createCredentials(String login, String pass, String ssh) throws RestServerException, ServiceException { HttpPost httpPost = new HttpPost(RMConfig.get().getRestUrl() + "/scheduler/createcredential"); try { MultipartEntity entity = createLoginPasswordSSHKeyMultipart(login, pass, ssh); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); String responseAsString = convertToString(response.getEntity().getContent()); switch (response.getStatusLine().getStatusCode()) { case 200: return responseAsString; default: throw new RestServerException(response.getStatusLine().getStatusCode(), responseAsString); } } catch (Exception e) { LOGGER.warn("Failed to create credentials", e); throw new ServiceException(e.getMessage()); } finally { httpPost.releaseConnection(); } }
private static void fileUpload() throws Exception { file = new File("/home/vigneshwaran/VIGNESH/dinesh.txt"); httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("ssd", new StringBody(ssd)); mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into slingfile.com"); HttpResponse response = httpclient.execute(httppost); // HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); }
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"); } }
private static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", sidcookie); file = new File("h:/install.txt"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("filepc", cbFile); mpEntity.addPart("server", new StringBody(server)); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into uploadbox.com"); HttpResponse response = httpclient.execute(httppost); System.out.println(response.getStatusLine()); uploadresponse = response.getLastHeader("Location").getValue(); uploadresponse = getData(uploadresponse); downloadlink = parseResponse(uploadresponse, "name=\"loadlink\" id=\"loadlink\" class=\"text\" onclick=\"this.select();\" value=\"", "\""); deletelink = parseResponse(uploadresponse, "name=\"deletelink\" id=\"deletelink\" class=\"text\" onclick=\"this.select();\" value=\"", "\""); System.out.println("Download link " + downloadlink); System.out.println("deletelink : " + deletelink); }
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); file = new File("h:/UploadingdotcomUploaderPlugin.java"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("emai", new StringBody("Free")); mpEntity.addPart("upload_range", new StringBody("1")); mpEntity.addPart("upfile_0", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into MegaShare.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); uploadresponse = response.getLastHeader("Location").getValue(); System.out.println("Upload response : "+uploadresponse); System.out.println(response.getStatusLine()); httpclient.getConnectionManager().shutdown(); }
private void fileUpload() throws Exception { httpPost = new NUHttpPost(postURL); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("MAX_FILE_SIZE", new StringBody(Long.toString(maxFileSizeLimit))); mpEntity.addPart("owner", new StringBody("")); mpEntity.addPart("pin", new StringBody(pin)); mpEntity.addPart("base", new StringBody(base)); mpEntity.addPart("host", new StringBody("letitbit.net")); mpEntity.addPart("source", new StringBody("newlib.wm-panel.com")); mpEntity.addPart("folder", new StringBody("")); mpEntity.addPart("file0", createMonitoredFileBody()); httpPost.setEntity(mpEntity); NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine()); uploading(); NULogger.getLogger().info("Now uploading your file into letitbit.net"); HttpResponse response = httpclient.execute(httpPost, httpContext); HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } // NULogger.getLogger().log(Level.INFO, "Upload response : {0}", uploadresponse); }
public void fileUpload() throws Exception { httpPost = new NUHttpPost("http://www.gigasize.com/uploadie"); MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uploadid)); mpEntity.addPart("sid", new StringBody(sid)); mpEntity.addPart("fileUpload1", createMonitoredFileBody()); httpPost.setEntity(mpEntity); uploading(); NULogger.getLogger().info("Now uploading your file into Gigasize..........................."); HttpResponse response = httpclient.execute(httpPost, httpContext); HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); if (resEntity != null) { sid = ""; sid = EntityUtils.toString(resEntity); NULogger.getLogger().log(Level.INFO, "After upload sid value : {0}", sid); } else { throw new Exception("There might be a problem with your internet connection or GigaSize server problem. Please try after some time :("); } }
/** * 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; }
@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(); } } }
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; }
@Test public void upload() throws IOException { String charset = "UTF-8"; HttpClient client = HttpClientBuilder.create().build(); String act = "upload"; HttpPost post = new HttpPost(getUploadUrl(act)); Map<String, Object> json = new HashMap<>(); json.put("name", "张三"); json.put("age", 23); String req = Base64.encodeBase64String(GsonUtil.toJson(json).getBytes(charset)); System.out.println("req:" + req); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("Api", StringBody.create("common", "text/plain", Charset.forName(charset))); reqEntity.addPart("data", StringBody.create(req, "text/plain", Charset.forName(charset))); reqEntity.addPart("img", new FileBody(new File("E:\\doc\\logo.jpg"))); post.setEntity(reqEntity); HttpResponse resp = client.execute(post); String line = resp.getStatusLine().toString(); Assert.assertEquals("HTTP/1.1 200 OK", line); HttpEntity resEntity = resp.getEntity(); Log.get("upload").info(EntityUtils.toString(resEntity, charset)); }
/** * Processes file upload information to extract the information regarding * the files from the device storage that needs to be uploaded to the remote * server * * @param postRequest * : {@link HttpPost} request object * * */ private MultipartEntity processFileUploadInfo(HttpPost postRequest) { String fileUploadInfo = this.requestFileUploadInfo; MultipartEntity fileUploadEntity = new MultipartEntity(); try { // Here we are receiving the JSONArray JSONArray fileInformation = new JSONArray(fileUploadInfo); Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->file information:" + fileUploadInfo); int totalFilesToUpload = fileInformation.length(); for (int currentIndex = 0; currentIndex < totalFilesToUpload; currentIndex++) { // add the file entry to the 'MultipartEntity' String fileToUploadType = fileInformation.getJSONObject(currentIndex).getString("imageType"); Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->fileToUploadType:" + fileToUploadType); if (fileToUploadType.equalsIgnoreCase(SmartConstants.FILE_UPLOAD_TYPE_URL)) { String filenameToUpload = fileInformation.getJSONObject(currentIndex).getString("imageData"); Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->fileToUpload:" + filenameToUpload); if (filenameToUpload.contains("file://")) { filenameToUpload = filenameToUpload.replace("file://", ""); } Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->NEW fileToUpload:" + filenameToUpload); File fileToUpload = new File(filenameToUpload); FileBody fileBody = new FileBody(fileToUpload); fileUploadEntity.addPart(fileInformation.getJSONObject(currentIndex).getString("name"), fileBody); } else if (fileToUploadType.equalsIgnoreCase(SmartConstants.FILE_UPLOAD_TYPE_DATA)) { // TODO need to add handling for Base64 content uploading byte[] fileContent = Base64.decode(fileInformation.getJSONObject(currentIndex).getString("imageData"), Base64.DEFAULT); ByteArrayBody fileByteArrayBody = new ByteArrayBody(fileContent, null); fileUploadEntity.addPart(fileInformation.getJSONObject(currentIndex).getString("name"), fileByteArrayBody); } } } catch (JSONException je) { // TODO need to handle this exception Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->JSONException:" + je.getMessage()); } catch (Exception e) { Log.d(SmartConstants.APP_NAME, "HttpUtility->processFileUploadInfo->Exception:" + e.getMessage()); } return fileUploadEntity; }
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } if (resEntity != null) { resEntity.consumeContent(); } }
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; }
/** * 获取请求信息 * @param httpRequest HTTP请求 * @return HTTP协议内容 */ public static String getRequestInfo(HttpRequest httpRequest) { StringBuilder builder = new StringBuilder(); //请求行 builder.append(httpRequest.getRequestLine()).append('\n'); //请求头 for (Header header : httpRequest.getAllHeaders()) { builder.append(header.getName()).append(':').append(header.getValue()).append('\n'); } if (httpRequest instanceof HttpPost) { //空行 builder.append('\n'); //请求体 HttpEntity httpEntity = ((HttpPost)httpRequest).getEntity(); if (httpEntity instanceof MultipartEntity) { MultipartEntity multipartEntity = (MultipartEntity) httpEntity; builder.append(multipartEntity.toString()); } else { try { builder.append(EntityUtils.toString(httpEntity)); } catch (Exception e) { DebugLog.e(TAG, "getRequestInfo()", e); } } builder.append('\n'); } return builder.toString(); }
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; }
/** * Do a http post with the multipart content type. This method is usually * used to upload the large size content, such as uploading a file. * * @param url * @param formParams * @param accessor * @return * @throws IOException * @throws YNoteException */ public static HttpResponse doPostByMultipart(String url, Map<String, Object> formParams, OAuthAccessor accessor) throws IOException, YNoteException { HttpPost post = new HttpPost(url); // for multipart encoded post, only sign with the oauth parameters // do not sign the our form parameters Header oauthHeader = getAuthorizationHeader(url, OAuthMessage.POST, null, accessor); if (formParams != null) { // encode our ynote parameters MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Entry<String, Object> parameter : formParams.entrySet()) { if (parameter.getValue() instanceof File) { // deal with file particular entity.addPart(parameter.getKey(), new FileBody((File)parameter.getValue())); } else if (parameter.getValue() != null){ entity.addPart(parameter.getKey(), new StringBody( parameter.getValue().toString(), Charset.forName(YNoteConstants.ENCODING))); } } post.setEntity(entity); } post.addHeader(oauthHeader); HttpResponse response = client.execute(post); if ((response.getStatusLine().getStatusCode() / 100) != 2) { YNoteException e = wrapYNoteException(response); throw e; } return response; }
public CustomRequest(final Activity activity, final String url, final MultipartEntity multipartEntity, final ResponseAction responseAction) { super(Method.POST, Globals.apiUrl + url, new Response.Listener<String>() { @Override public void onResponse(String response) { Tools.hideLoadingDialog(); Log.d("Volley Response - " + activity.getClass().getSimpleName(), "----" + response); try { JSONObject res = new JSONObject(response); //set sid if not already set if (res.has("sid")) { (new MySharedPreferences(activity)).saveToPreferences("sid", res.getString("sid")); } // set custom response tasks responseAction.onResponseAction(res); } catch (JSONException e) { Tools.hideLoadingDialog(); Tools.makeToast(activity, activity.getString(R.string.error_occured), Toast.LENGTH_SHORT, -1); Log.e("Volley Response - " + activity.getClass().getSimpleName(), "----" + e.getMessage()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Error.Response On Main Server - " + activity.getClass().getSimpleName(), "----" + error); Tools.hideLoadingDialog(); Tools.makeToast(activity, activity.getString(R.string.error_occured), Toast.LENGTH_SHORT, -1); responseAction.onErrorAction(error); } }); this.context = activity; this.entity = multipartEntity; this.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); }
/** * 设置用户所在组织的形象设置 * * @param title * 软件标题 * @param windowsLogoFile * windows客户端显示的Logo,为null时代表清除Logo。 * @param androidLogoFile * android客户端显示的Logo,为null时代表清除Logo。 * @throws Exception */ public void setVi(String title, File windowsLogoFile, File androidLogoFile, String group) throws Exception { LOG.info("Update vi group of "+ group +" using title:"+title +",windowLogoPath:" + windowsLogoFile +",androidLogoPath:" + androidLogoFile); MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")); if (title == null) { title = ""; } entity.addPart("clientTitle",new StringBody(title, Charset.forName("UTF-8"))); if (windowsLogoFile != null) { entity.addPart(LOGO_FOR_WINDOWS, new FileBody(windowsLogoFile)); } else { entity.addPart(LOGO_FOR_WINDOWS, new StringBody("")); } if (androidLogoFile != null) { entity.addPart(LOGO_FOR_ANDROID, new FileBody(androidLogoFile)); } else { entity.addPart(LOGO_FOR_ANDROID, new StringBody("")); } String url = getSetViUrl(group); postMultipartEntity(entity,url); }
/** * 设置用户所在组织所用的Android客户端软件的Logo * * @param androidLogoFile * 为null时代表清除Logo。 * @throws Exception */ public void setViAndroidLogo(File androidLogoFile,String group) throws Exception { MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")); if (androidLogoFile != null) { entity.addPart(LOGO_FOR_ANDROID, new FileBody(androidLogoFile)); } else { entity.addPart(LOGO_FOR_ANDROID, new StringBody("")); } String url = getSetViUrl(group); postMultipartEntity(entity,url); }
/** * 设置用户所在组织所用的Windows客户端软件的Logo * * @param windowsLogoFile * 为null时代表清除Logo。 * @throws Exception */ public void setViWindowsLogo(File windowsLogoFile,String group) throws Exception { MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")); if (windowsLogoFile != null) { entity.addPart(LOGO_FOR_WINDOWS, new FileBody(windowsLogoFile)); } else { entity.addPart(LOGO_FOR_WINDOWS, new StringBody("")); } String url = getSetViUrl(group); postMultipartEntity(entity,url); }
/** * 设置用户所在组织所用的客户端软件的标题 * * @param title * @throws Exception */ public void setViTitle(String title,String group) throws Exception { MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")); if (title == null) { title = ""; } entity.addPart("clientTitle", new StringBody(title, Charset.forName("UTF-8"))); String url = getSetViUrl(group); postMultipartEntity(entity,url); }
private void postMultipartEntity(MultipartEntity entity,String url) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); System.out.println(url); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost, localContext); if (response.getStatusLine().getStatusCode() == 200) { System.out.println("OK!"); } else { throw new Exception(String.valueOf(response.getStatusLine() .getStatusCode())); } }
@Test public void testPostRequestWithMultipartEncodedParameters() throws Exception { this.testServer.response = "testPostRequestWithMultipartEncodedParameters"; HttpPost httppost = new HttpPost("http://localhost:8192/"); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("age", new StringBody("120")); reqEntity.addPart("gender", new StringBody("Male")); httppost.setEntity(reqEntity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = this.httpclient.execute(httppost, responseHandler); assertEquals("POST:testPostRequestWithMultipartEncodedParameters-params=2;age=120;gender=Male", responseBody); }
public Observable<String> sendPostUploadFile(InputStream inputStream, String filename, String pid, Map<String, String> parameters) { return Observable.create(o -> { try { postConfigureStart(pid, parameters); // загрузка файла InputStreamBody bin = new InputStreamBody(inputStream, filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bundlefile", bin); reqEntity.addPart("action", new StringBody("install")); reqEntity.addPart("bundlestart", new StringBody("start")); reqEntity.addPart("bundlestartlevel", new StringBody("1")); postHttpClientQuery(URL_BUNDLES, reqEntity, Collections .list(new BasicHeader("Accept", "application/json"))); o.onNext(""); } catch (Exception e) { throw Exceptions.propagate(e); } o.onCompleted(); }).subscribeOn(Schedulers.from(mes)).cast(String.class); }
public List<BESAPI.SiteFile> updateFile(String siteType, String site, long id, File file) throws URISyntaxException{ URI uri = new URIBuilder(baseURI).setPath(Paths.file(site,siteType,id)).build(); MultipartEntity reqEntity = new MultipartEntity(); FileBody uploadFilePart = new FileBody(file); reqEntity.addPart("file", uploadFilePart); try { HttpResponse response = client.execute(Request.Post(uri).body(reqEntity)).returnResponse(); return getContent(response,BESAPI.SiteFile.class); } catch (Exception e) { throw new RuntimeException(e); } }
public List<BESAPI.SiteFile> createFiles(String siteType, String site, File... files) throws URISyntaxException{ URI uri = new URIBuilder(baseURI).setPath(Paths.files(site,siteType)).build(); MultipartEntity reqEntity = new MultipartEntity(); for(File file:files){ FileBody uploadFilePart = new FileBody(file); reqEntity.addPart("file", uploadFilePart); } try { HttpResponse response = client.execute(Request.Post(uri).body(reqEntity)).returnResponse(); return getContent(response,BESAPI.SiteFile.class); } catch (Exception e) { throw new RuntimeException(e); } }
private static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://upbooth.com/uploadHandler.php?r=upbooth.com&p=http?aff=1db2f3b654350bf4"); httppost.addHeader("Cookie", fileHostingCookie); file = new File("c:/Dinesh/Naruto_Face.jpg"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); String cookie = fileHostingCookie.substring(fileHostingCookie.indexOf("=") + 1); cookie = cookie.substring(0, cookie.indexOf(";")); System.out.println(cookie); mpEntity.addPart("=_sessionid", new StringBody(cookie)); mpEntity.addPart("files[]", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into upbooth.com"); HttpResponse response = httpclient.execute(httppost); // HttpEntity resEntity = response.getEntity(); String uploadresponse = EntityUtils.toString(response.getEntity()); System.out.println(response.getStatusLine()); // if (resEntity != null) { // uploadresponse = EntityUtils.toString(resEntity); // } // System.out.println("Upload response : " + uploadresponse); String downloadlink = parseResponse(uploadresponse, "\"url\":\"", "\""); downloadlink = downloadlink.replaceAll("\\\\", ""); String deletelink = parseResponse(uploadresponse, "\"delete_url\":\"", "\""); deletelink = deletelink.replaceAll("\\\\", ""); System.out.println("Download link : " + downloadlink); System.out.println("Delete link : " + deletelink); }
public static MultipartEntity encodePOSTUrl(MultipartEntity mEntity, Bundle parameters) { if (parameters != null && parameters.size() > 0) { boolean first = true; for (String key : parameters.keySet()) { if (key != null) { if (first) { first = false; } String value = ""; Object object = parameters.get(key); if (object != null) { value = String.valueOf(object); } try { mEntity.addPart(key, new StringBody(value)); } catch (Exception e) { e.printStackTrace(); } } } } return mEntity; }
/** * Constructs application/form-data entity based upon the specified parameters. * * @param formParams * form parameters * @return request application/form-data entity for the service */ private static HttpEntity constructFormDataEntity(List<ExecutionFormParam> formParams) { MultipartEntity entity = new MultipartEntity(); try { for (ExecutionFormParam formParam : formParams) { if (formParam.getValues() != null) { for (String value : formParam.getValues()) { entity.addPart(formParam.getName(), new StringBody(value, Consts.UTF_8)); } } else if (formParam.getFiles() != null) { for (FileValue fileValue : formParam.getFiles()) { FileBody fileBody = new FileBody(fileValue.getFile(), fileValue.getFilename(), fileValue.getMimetype(), null); entity.addPart(formParam.getName(), fileBody); } } else { entity.addPart(formParam.getName(), new StringBody("", Consts.UTF_8)); } } } catch (UnsupportedEncodingException e) { throw new WrdzRuntimeException("The encoding " + Consts.UTF_8 + " is not supported"); } return entity; }
public static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); file = new File("H:\\FileServeUploader.java"); // if(!username.isEmpty() && !password.isEmpty()) // postURL = megauploadlink + "upload_done.php?UPLOAD_IDENTIFIER=" + uploadID + "&user=undefined&s=" + filelength; // else // postURL = megauploadlink + "upload_done.php?UPLOAD_IDENTIFIER=" + uploadID + "&"+usercookie+"&s=" + filelength; HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", uprandcookie + ";" + autologincookie); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("MAX_FILE_SIZE", new StringBody("2097152000")); mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uid)); mpEntity.addPart("go", new StringBody("1")); mpEntity.addPart("files", cbFile); httppost.setEntity(mpEntity); System.out.println("Now uploading your file into depositfiles..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); downloadlink = parseResponse(uploadresponse, "ud_download_url = '", "'"); deletelink = parseResponse(uploadresponse, "ud_delete_url = '", "'"); System.out.println("download link : " + downloadlink); System.out.println("delete link : " + deletelink); } }
public void fileUpload() throws Exception { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", FileSonicAccount.getLangcookie() + ";" + FileSonicAccount.getSessioncookie() + ";" + FileSonicAccount.getMailcookie() + ";" + FileSonicAccount.getNamecookie() + ";" + FileSonicAccount.getRolecookie() + ";"); MultipartEntity mpEntity = new MultipartEntity(); //ContentBody cbFile = new FileBody(file); mpEntity.addPart("files[]", createMonitoredFileBody()); httppost.setEntity(mpEntity); uploading(); NULogger.getLogger().info("Now uploading your file into filesonic..........................."); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); if (resEntity != null) { String tmp = EntityUtils.toString(resEntity); //NULogger.getLogger().info("response : " + tmp); } uploadresponse = response.getLastHeader("Location").getValue(); NULogger.getLogger().log(Level.INFO, "Upload response URL : {0}", uploadresponse); uploadresponse = getData(uploadresponse); if (uploadresponse.contains("File was successfully uploaded")) { NULogger.getLogger().info("File was successfully uploaded :)"); uploadFinished(); } else { throw new Exception("There might be a problem with your internet connecivity or server error. Please try after some time. :("); } }