List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:org.deviceconnect.android.profile.restful.test.NormalFileDescriptorProfileTestCase.java
/** * ????./* w w w .java 2s .c o m*/ * <pre> * ?HTTP * Method: PUT * Path: /file_descriptor/write?deviceid=xxxx&mediaid=xxxx * Entity: "test" * </pre> * <pre> * ?? * result?0??????? * </pre> */ public void testWrite001() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/" + FileDescriptorProfileConstants.PROFILE_NAME); builder.append("/" + FileDescriptorProfileConstants.ATTRIBUTE_WRITE); builder.append("?"); builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=" + getDeviceId()); builder.append("&"); builder.append(FileDescriptorProfileConstants.PARAM_PATH + "=test.txt"); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken()); try { MultipartEntity entity = new MultipartEntity(); entity.addPart("media", new StringBody("test")); HttpPut request = new HttpPut(builder.toString()); request.addHeader("Content-Disposition", "form-data; name=\"media\"; filename=\"test.txt\""); request.setEntity(entity); JSONObject root = sendRequest(request); Assert.assertNotNull("root is null.", root); assertResultOK(root); } catch (JSONException e) { fail("Exception in JSONObject." + e.getMessage()); } catch (UnsupportedEncodingException e) { fail("Exception in StringBody." + e.getMessage()); } }
From source file:org.deviceconnect.android.profile.restful.test.NormalFileDescriptorProfileTestCase.java
/** * ????./*www . jav a 2s.c o m*/ * <pre> * ?HTTP * Method: PUT * Path: /file_descriptor/write?deviceid=xxxx&mediaid=xxxx&position=xxx * Entity: "test" * </pre> * <pre> * ?? * result?0??????? * </pre> */ public void testWrite002() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/" + FileDescriptorProfileConstants.PROFILE_NAME); builder.append("/" + FileDescriptorProfileConstants.ATTRIBUTE_WRITE); builder.append("?"); builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=" + getDeviceId()); builder.append("&"); builder.append(FileDescriptorProfileConstants.PARAM_PATH + "=test.txt"); builder.append("&"); builder.append(FileDescriptorProfileConstants.PARAM_POSITION + "=0"); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken()); try { MultipartEntity entity = new MultipartEntity(); entity.addPart("media", new StringBody("test")); HttpPut request = new HttpPut(builder.toString()); request.addHeader("Content-Disposition", "form-data; name=\"media\"; filename=\"test.txt\""); request.setEntity(entity); JSONObject root = sendRequest(request); Assert.assertNotNull("root is null.", root); assertResultOK(root); } catch (JSONException e) { fail("Exception in JSONObject." + e.getMessage()); } catch (UnsupportedEncodingException e) { fail("Exception in StringBody." + e.getMessage()); } }
From source file:org.thomwiggers.Jjoyce.comet.CometJoyceClientRelay.java
public void sendStream(String token, Stream stream, boolean blocking) { if (!this.token.equals(token)) throw new IllegalArgumentException("Wrong token!"); this.conditionMessageIn = lock.newCondition(); this.conditionOut = lock.newCondition(); MultipartEntity multipartStream = new MultipartEntity(); multipartStream.addPart("stream", stream); final HttpPost post = new HttpPost( String.format("http://%s:%s%s?m=%s", hub.getHost(), hub.getPort(), hub.getPath())); post.setEntity(multipartStream);//w w w . ja v a 2s. c om Thread t = new Thread(new Runnable() { public void run() { try { httpClient.execute(post); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); t.start(); if (blocking) { try { t.join(); } catch (InterruptedException e) { } } }
From source file:org.andrico.andrico.facebook.FBBase.java
private MultipartEntity makeMultipartEntityFromParameters(FBMethod method, ByteArrayBody.WriteToProgressHandler runnable) throws UnsupportedEncodingException { MultipartEntity multipartEntity = new MultipartEntity(); for (String key : method.mParameters.keySet()) { multipartEntity.addPart(key, new StringBody(method.mParameters.get(key))); }/*from ww w . j a va 2 s.c o m*/ multipartEntity.addPart("data", new ByteArrayBody(method.mData, method.mDataFilename, runnable)); return multipartEntity; }
From source file:org.bimserver.client.Channel.java
public long checkin(String baseAddress, String token, long poid, String comment, long deserializerOid, boolean merge, boolean sync, long fileSize, String filename, InputStream inputStream) throws ServerException, UserException { String address = baseAddress + "/upload"; DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); }//from w ww . j a v a 2 s.c o m } }); httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); HttpPost httppost = new HttpPost(address); try { // TODO find some GzipInputStream variant that _compresses_ instead of _decompresses_ using deflate for now InputStreamBody data = new InputStreamBody(new DeflaterInputStream(inputStream), filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("data", data); reqEntity.addPart("token", new StringBody(token)); reqEntity.addPart("deserializerOid", new StringBody("" + deserializerOid)); reqEntity.addPart("merge", new StringBody("" + merge)); reqEntity.addPart("poid", new StringBody("" + poid)); reqEntity.addPart("comment", new StringBody("" + comment)); reqEntity.addPart("sync", new StringBody("" + sync)); reqEntity.addPart("compression", new StringBody("deflate")); httppost.setEntity(reqEntity); HttpResponse httpResponse = httpclient.execute(httppost); if (httpResponse.getStatusLine().getStatusCode() == 200) { JsonParser jsonParser = new JsonParser(); JsonElement result = jsonParser .parse(new JsonReader(new InputStreamReader(httpResponse.getEntity().getContent()))); if (result instanceof JsonObject) { JsonObject jsonObject = (JsonObject) result; if (jsonObject.has("exception")) { JsonObject exceptionJson = jsonObject.get("exception").getAsJsonObject(); String exceptionType = exceptionJson.get("__type").getAsString(); String message = exceptionJson.has("message") ? exceptionJson.get("message").getAsString() : "unknown"; if (exceptionType.equals(UserException.class.getSimpleName())) { throw new UserException(message); } else if (exceptionType.equals(ServerException.class.getSimpleName())) { throw new ServerException(message); } } else { return jsonObject.get("checkinid").getAsLong(); } } } } catch (ClientProtocolException e) { LOGGER.error("", e); } catch (IOException e) { LOGGER.error("", e); } return -1; }
From source file:org.oscarehr.common.service.E2ESchedulerJob.java
@Override public void run() { DemographicDao demographicDao = SpringUtils.getBean(DemographicDao.class); OscarLogDao oscarLogDao = SpringUtils.getBean(OscarLogDao.class); StringBuilder sb = new StringBuilder(255); int success = 0; int failure = 0; int skipped = 0; int diffDays = 14; List<Integer> ids = null; try {//w w w. ja va2 s .c om // Gather demographic numbers for specified mode of operation if (diffMode) { if (e2eDiffDays != null && StringUtils.isNumeric(e2eDiffDays)) { diffDays = Integer.parseInt(e2eDiffDays); } Calendar cal = GregorianCalendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, -diffDays); ids = oscarLogDao.getDemographicIdsOpenedSinceTime(cal.getTime()); } else { ids = demographicDao.getActiveDemographicIds(); } if (ids != null) Collections.sort(ids); // Log Start Header StringBuilder sbStart = reuseStringBuilder(sb); sbStart.append("Starting E2E export job\nE2E Target URL: ").append(e2eUrl); if (diffMode) { sbStart.append("\nExport Mode: Differential - Days: ").append(diffDays); } else { sbStart.append("\nExport Mode: Full"); } logger.info(sbStart.toString()); StringBuilder sbStartRec = reuseStringBuilder(sb); sbStartRec.append(ids.size()).append(" records pending"); if (ids.size() > 0) { sbStartRec.append("\nRange: ").append(ids.get(0)).append(" - ").append(ids.get(ids.size() - 1)); sbStartRec.append(", Median: ").append(ids.get((ids.size() - 1) / 2)); } logger.info(sbStartRec.toString()); long startJob = System.currentTimeMillis(); long endJob = startJob; for (Integer id : ids) { // Select Template E2EVelocityTemplate t = new E2EVelocityTemplate(); // Create and load Patient data long startLoad = System.currentTimeMillis(); E2EPatientExport patient = new E2EPatientExport(); patient.setExAllTrue(); long endLoad = startLoad; long startTemplate = 0; long endTemplate = startTemplate; // Load patient data and merge to template String output = ""; if (patient.loadPatient(id.toString())) { endLoad = System.currentTimeMillis(); if (patient.isActive()) { startTemplate = System.currentTimeMillis(); output = t.export(patient); endTemplate = System.currentTimeMillis(); } else { logger.info("[Demo: ".concat(id.toString()).concat("] Not active - skipped")); skipped++; continue; } } else { endLoad = System.currentTimeMillis(); logger.error("[Demo: ".concat(id.toString()).concat("] Failed to load")); failure++; continue; } long startPost = System.currentTimeMillis(); long endPost = startPost; // Attempt to perform HTTP POST request try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(e2eUrl); // Assemble Multi-part Request StringBuilder sbFile = reuseStringBuilder(sb); sbFile.append("output_").append(id).append(".xml"); ByteArrayBody body = new ByteArrayBody(output.getBytes(), "text/xml", sbFile.toString()); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("content", body); httpPost.setEntity(reqEntity); // Send HTTP POST request HttpResponse response = httpclient.execute(httpPost); if (response != null && response.getStatusLine().getStatusCode() == 201) { success++; } else { logger.warn(response.getStatusLine()); failure++; } } catch (HttpHostConnectException e) { logger.error("Connection to ".concat(e2eUrl).concat(" refused")); failure++; } catch (NoRouteToHostException e) { logger.error("Can't resolve route to ".concat(e2eUrl)); failure++; } catch (Exception e) { logger.error("Error", e); failure++; } finally { endPost = System.currentTimeMillis(); } // Log Record completion + benchmarks StringBuilder sbTimer = reuseStringBuilder(sb); sbTimer.append("[Demo: ").append(id); sbTimer.append("] L:").append((endLoad - startLoad) / 1000.0); sbTimer.append(" T:").append((endTemplate - startTemplate) / 1000.0); sbTimer.append(" P:").append((endPost - startPost) / 1000.0); logger.info(sbTimer.toString()); } endJob = System.currentTimeMillis(); logger.info("Done E2E export job (" + convertTime(endJob - startJob) + ")"); } catch (Throwable e) { logger.error("Error", e); logger.info("E2E export job aborted"); } finally { // Log final record counts int unaccounted = ids.size() - success - failure - skipped; sb = reuseStringBuilder(sb); sb.append(success).append(" records processed"); if (failure > 0) sb.append("\n").append(failure).append(" records failed"); if (skipped > 0) sb.append("\n").append(skipped).append(" records skipped"); if (unaccounted > 0) sb.append("\n").append(unaccounted).append(" records unaccounted"); logger.info(sb.toString()); DbConnectionFilter.releaseAllThreadDbResources(); } }
From source file:org.jboss.as.test.smoke.mgmt.servermodule.HttpGenericOperationUnitTestCase.java
/** * Execute the post request.// www .j a v a 2 s . co m * * @param operation the operation body * @param encoded whether it should send the dmr encoded header * @param streams the optional input streams * @return the response from the server * @throws IOException */ private ModelNode executePost(final ContentBody operation, final boolean encoded, final List<ContentBody> streams) throws IOException { final HttpPost post = new HttpPost(uri); final MultipartEntity entity = new MultipartEntity(); entity.addPart("operation", operation); for (ContentBody stream : streams) { entity.addPart("input-streams", stream); } post.setEntity(entity); return parseResponse(httpClient.execute(post), encoded); }
From source file:org.apache.sling.testing.tools.sling.SlingClient.java
/** Updates a node at specified path, with optional properties *//* w w w. ja v a 2 s. c o m*/ public void setProperties(String path, Map<String, Object> properties) throws IOException { final MultipartEntity entity = new MultipartEntity(); // Add user properties if (properties != null) { for (Map.Entry<String, Object> e : properties.entrySet()) { entity.addPart(e.getKey(), new StringBody(e.getValue().toString())); } } final HttpResponse response = executor .execute(builder.buildPostRequest(path).withEntity(entity).withCredentials(username, password)) .assertStatus(200).getResponse(); }
From source file:cc.mincai.android.desecret.storage.dropbox.DropboxClient.java
/** * Put a file in the user's Dropbox./*from w ww . jav a 2 s . c o m*/ */ @SuppressWarnings("unchecked") public HttpResponse putFile(String root, String to_path, File file_obj) throws DropboxException { String path = "/files/" + root + to_path; HttpClient client = getClient(); try { String target = buildFullURL(secureProtocol, content_host, this.port, buildURL(path, API_VERSION, null)); HttpPost req = new HttpPost(target); // this has to be done this way because of how oauth signs params // first we add a "fake" param of file=path of *uploaded* file // THEN we sign that. List nvps = new ArrayList(); nvps.add(new BasicNameValuePair("file", file_obj.getName())); req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); auth.sign(req); // now we can add the real file multipart and we're good MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(file_obj); entity.addPart("file", bin); // this resets it to the new entity with the real file req.setEntity(entity); HttpResponse resp = client.execute(req); resp.getEntity().consumeContent(); return resp; } catch (Exception e) { throw new DropboxException(e); } }
From source file:ninja.utils.NinjaTestBrowser.java
public String uploadFile(String url, String paramName, File fileToUpload) { String response = null;// w ww.jav a 2 s . c o m try { httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // For File parameters entity.addPart(paramName, new FileBody((File) fileToUpload)); post.setEntity(entity); // Here we go! response = EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8"); post.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } return response; }