List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity(final HttpMultipartMode mode)
From source file:com.iia.giveastick.util.RestClient.java
private HttpEntity buildMultipartEntity(JSONObject jsonParams) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try {/*from www . j a v a 2 s. c o m*/ String path = jsonParams.getString("file"); if (debugWeb && GiveastickApplication.DEBUG) { Log.d(TAG, "key : file value :" + path); } if (!TextUtils.isEmpty(path)) { // File entry File file = new File(path); FileBody fileBin = new FileBody(file, "application/octet"); entity.addPart("file", fileBin); try { entity.addPart("file", new StringBody(path, "text/plain", Charset.forName(HTTP.UTF_8))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return entity; }
From source file:com.qsoft.components.gallery.utils.GalleryUtils.java
private static MultipartEntity addParamsForUpload(File file, String imageType, String imageName, Long equipmentId, Long userId, String locationDTO, Long equipmentHistoryId) throws UnsupportedEncodingException { MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart(ConstantImage.IMAGE_FILE, new FileBody(file)); mpEntity.addPart(ConstantImage.IMAGE_TYPE, new StringBody(imageType.toUpperCase())); mpEntity.addPart(ConstantImage.IMAGE_NAME, new StringBody(imageName.toUpperCase())); if (equipmentId != null) { mpEntity.addPart(ConstantImage.EQUIPMENT_ID, new StringBody(equipmentId.toString())); }/* www . ja v a2s .c o m*/ if (userId != null) { mpEntity.addPart(ConstantImage.USER_ID, new StringBody(userId.toString())); } if (equipmentHistoryId != null) { mpEntity.addPart(ConstantImage.EQUIPMENTHISTORY_ID, new StringBody(equipmentHistoryId.toString())); } mpEntity.addPart(ConstantImage.IMAGE_LOCATION_DTO, new StringBody(locationDTO)); return mpEntity; }
From source file:com.mutu.gpstracker.breadcrumbs.UploadBreadcrumbsTrackTask.java
/** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token./*from w w w . ja v a 2 s .c o m*/ */ @Override protected Uri doInBackground(Void... params) { // Leave room in the progressbar for uploading determineProgressGoal(); mProgressAdmin.setUpload(true); // Build GPX file Uri gpxFile = exportGpx(); if (isCancelled()) { String text = mContext.getString(R.string.ticker_failed) + " \"http://api.gobreadcrumbs.com/v1/tracks\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Fail to execute request due to canceling"), text); } // Collect GPX Import option params mActivityId = null; mBundleId = null; mDescription = null; mIsPublic = null; Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); Cursor cursor = null; try { cursor = mContext.getContentResolver().query(metadataUri, new String[] { MetaData.KEY, MetaData.VALUE }, null, null, null); if (cursor.moveToFirst()) { do { String key = cursor.getString(0); if (BreadcrumbsTracks.ACTIVITY_ID.equals(key)) { mActivityId = cursor.getString(1); } else if (BreadcrumbsTracks.BUNDLE_ID.equals(key)) { mBundleId = cursor.getString(1); } else if (BreadcrumbsTracks.DESCRIPTION.equals(key)) { mDescription = cursor.getString(1); } else if (BreadcrumbsTracks.ISPUBLIC.equals(key)) { mIsPublic = cursor.getString(1); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } if ("-1".equals(mActivityId)) { String text = "Unable to upload without a activity id stored in meta-data table"; IllegalStateException e = new IllegalStateException(text); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text); } int statusCode = 0; String responseText = null; Uri trackUri = null; HttpEntity responseEntity = null; try { if ("-1".equals(mBundleId)) { mBundleDescription = "";//mContext.getString(R.string.breadcrumbs_bundledescription); mBundleName = mContext.getString(R.string.app_name); mBundleId = createOpenGpsTrackerBundle(); } String gpxString = XmlCreator .convertStreamToString(mContext.getContentResolver().openInputStream(gpxFile)); HttpPost method = new HttpPost("http://api.gobreadcrumbs.com:80/v1/tracks"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("import_type", new StringBody("GPX")); //entity.addPart("gpx", new FileBody(gpxFile)); entity.addPart("gpx", new StringBody(gpxString)); entity.addPart("bundle_id", new StringBody(mBundleId)); entity.addPart("activity_id", new StringBody(mActivityId)); entity.addPart("description", new StringBody(mDescription)); // entity.addPart("difficulty", new StringBody("3")); // entity.addPart("rating", new StringBody("4")); entity.addPart("public", new StringBody(mIsPublic)); method.setEntity(entity); // Execute the POST to OpenStreetMap mConsumer.sign(method); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "HTTP Method " + method.getMethod()); Log.d(TAG, "URI scheme " + method.getURI().getScheme()); Log.d(TAG, "Host name " + method.getURI().getHost()); Log.d(TAG, "Port " + method.getURI().getPort()); Log.d(TAG, "Request path " + method.getURI().getPath()); Log.d(TAG, "Consumer Key: " + mConsumer.getConsumerKey()); Log.d(TAG, "Consumer Secret: " + mConsumer.getConsumerSecret()); Log.d(TAG, "Token: " + mConsumer.getToken()); Log.d(TAG, "Token Secret: " + mConsumer.getTokenSecret()); Log.d(TAG, "Execute request: " + method.getURI()); for (Header header : method.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpClient.execute(method); mProgressAdmin.addUploadProgress(); statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); responseText = XmlCreator.convertStreamToString(stream); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Upload Response: " + responseText); } Pattern p = Pattern.compile(">([0-9]+)</id>"); Matcher m = p.matcher(responseText); if (m.find()) { Integer trackId = Integer.valueOf(m.group(1)); trackUri = Uri.parse("http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx"); for (File photo : mPhotoUploadQueue) { uploadPhoto(photo, trackId); } } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "A problem during communication"); } finally { if (responseEntity != null) { try { //EntityUtils.consume(responseEntity); responseEntity.consumeContent(); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } if (statusCode == 200 || statusCode == 201) { if (trackUri == null) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Unable to retrieve URI from response"), responseText); } } else { //mAdapter.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Status code: " + statusCode), responseText); } return trackUri; }
From source file:ecblast.test.EcblastTest.java
public String executeCompareReactions(File queryFile, File targetFile) { String urlString = "http://localhost:8080/ecblast-rest/compare"; DefaultHttpClient client;/*www. jav a 2 s .co m*/ client = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(urlString); try { //Set various attributes MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody queryFileBody = new FileBody(queryFile); //Prepare payload multiPartEntity.addPart("q", queryFileBody); multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8"))); FileBody targetFileBody = new FileBody(targetFile); multiPartEntity.addPart("t", targetFileBody); multiPartEntity.addPart("T", new StringBody("RXN", "text/plain", Charset.forName("UTF-8"))); //Set to request body postRequest.setEntity(multiPartEntity); //Send request HttpResponse response = client.execute(postRequest); //Verify response if any if (response != null) { System.out.println(response.getStatusLine().getStatusCode()); return response.toString(); } } catch (IOException ex) { return null; } return null; }
From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java
@Test public void testMultiPartIndividualFileToLarge() throws IOException { TestHttpClient client = new TestHttpClient(); try {// ww w .jav a 2s .co m String uri = DefaultServer.getDefaultServerURL() + "/servletContext/3"; HttpPost post = new HttpPost(uri); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8)); entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile()))); post.setEntity(entity); HttpResponse result = client.execute(post); String response = HttpClientUtils.readResponse(result); Assert.assertEquals("TEST FAILED: wrong response code\n" + response, StatusCodes.INTERNAL_SERVER_ERROR, result.getStatusLine().getStatusCode()); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.nominanuda.web.http.ServletHelper.java
@SuppressWarnings("unchecked") private HttpEntity buildEntity(HttpServletRequest servletRequest, final InputStream is, long contentLength, String ct, String cenc) throws IOException { if (ServletFileUpload.isMultipartContent(servletRequest)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items; try {/*from w ww.j ava 2 s. c o m*/ items = upload.parseRequest(new HttpServletRequestWrapper(servletRequest) { public ServletInputStream getInputStream() throws IOException { return new ServletInputStream() { public int read() throws IOException { return is.read(); } public int read(byte[] arg0) throws IOException { return is.read(arg0); } public int read(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } //@Override @SuppressWarnings("unused") public boolean isFinished() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public boolean isReady() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public void setReadListener(ReadListener arg0) { Check.illegalstate.fail(NOT_IMPLEMENTED); } }; } }); } catch (FileUploadException e) { throw new IOException(e); } MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (FileItem i : items) { multipartEntity.addPart(i.getFieldName(), new InputStreamBody(i.getInputStream(), i.getName())); } return multipartEntity; } else { InputStreamEntity entity = new InputStreamEntity(is, contentLength); entity.setContentType(ct); if (cenc != null) { entity.setContentEncoding(cenc); } return entity; } }
From source file:com.glasshack.checkmymath.CheckMyMath.java
public String post(String url, List<NameValuePair> nameValuePairs) { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); String readableResponse = null; try {//from w w w .j a v a2 s . co m MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < nameValuePairs.size(); index++) { if (nameValuePairs.get(index).getName().equalsIgnoreCase("file")) { // If the key equals to "file", we use FileBody to transfer the data entity.addPart("file", new FileBody(new File(nameValuePairs.get(index).getValue()), "image/jpeg")); } else { // Normal string data entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue())); } } httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost, localContext); readableResponse = EntityUtils.toString(response.getEntity(), "UTF-8"); Log.e("response", readableResponse); } catch (IOException e) { e.printStackTrace(); } return readableResponse; }
From source file:org.wso2.am.integration.tests.other.InvalidAuthTokenLargePayloadTestCase.java
/** * Upload a file to the given URL//from w w w .j a v a2 s. co m * * @param endpointUrl URL to be file upload * @param fileName Name of the file to be upload * @throws IOException throws if connection issues occurred */ private HttpResponse uploadFile(String endpointUrl, File fileName, Map<String, String> headers) throws IOException { //open import API url connection and deploy the exported API URL url = new URL(endpointUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(fileName); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); //setting headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); if (key != null) { connection.setRequestProperty(key, headers.get(key)); } } for (String key : headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); } } OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = connection.getResponseCode(); BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream())); String temp; StringBuilder responseMsg = new StringBuilder(); while ((temp = read.readLine()) != null) { responseMsg.append(temp); } HttpResponse response = new HttpResponse(responseMsg.toString(), status); return response; }
From source file:com.frentix.restapi.RestConnection.java
/** * Attach file to POST request./*w w w . j av a 2s . com*/ * * @param post the request * @param filename the filename field * @param file the file * @throws UnsupportedEncodingException */ public void addMultipart(HttpEntityEnclosingRequestBase post, String filename, File file) throws UnsupportedEncodingException { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("filename", new StringBody(filename)); FileBody fileBody = new FileBody(file, "application/octet-stream"); entity.addPart("file", fileBody); post.setEntity(entity); }