List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE
HttpMultipartMode BROWSER_COMPATIBLE
To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.
Click Source Link
From source file:com.iia.giveastick.util.RestClient.java
private HttpEntity buildMultipartEntity(JSONObject jsonParams) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try {//from ww w . j av a 2 s .com 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:org.codelibs.fess.crawler.extractor.impl.ApiExtractor.java
@Override public ExtractData getText(InputStream in, Map<String, String> params) { if (logger.isDebugEnabled()) { logger.debug("Accessing " + url); }//from ww w .j a v a 2s . co m // start AccessTimeoutTarget accessTimeoutTarget = null; TimeoutTask accessTimeoutTask = null; if (accessTimeout != null) { accessTimeoutTarget = new AccessTimeoutTarget(Thread.currentThread()); accessTimeoutTask = TimeoutManager.getInstance().addTimeoutTarget(accessTimeoutTarget, accessTimeout.intValue(), false); } ExtractData data = new ExtractData(); HttpPost httpPost = new HttpPost(url); HttpEntity postEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .setCharset(Charset.forName("UTF-8")).addBinaryBody("filedata", in).build(); httpPost.setEntity(postEntity); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { if (response.getStatusLine().getStatusCode() != Constants.OK_STATUS_CODE) { logger.error( "Failed to access " + url + ", code: " + response.getStatusLine().getStatusCode() + "."); return null; } data.setContent(EntityUtils.toString(response.getEntity(), Charsets.UTF_8)); Header[] headers = response.getAllHeaders(); for (final Header header : headers) { data.putValue(header.getName(), header.getValue()); } } catch (IOException e) { throw new ExtractException(e); } finally { if (accessTimeout != null) { accessTimeoutTarget.stop(); if (!accessTimeoutTask.isCanceled()) { accessTimeoutTask.cancel(); } } } return data; }
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())); }//from w w w.j av a 2 s .com 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:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java
public void createNewApplication(String applicationName, String runtime, String appTypeName, String applicationRevision, String applicationDescription, String uploadedFileName, String runtimeProperties, String tags, File uploadArtifact, boolean isNewVersion, String applicationContext, String conSpec, boolean setDefaultVersion, String appCreationMethod, String gitRepoUrl, String gitRepoBranch, String projectRoot) throws AppCloudIntegrationTestException { HttpClient httpclient = null;/*from w ww .ja v a 2s .c o m*/ org.apache.http.HttpResponse response = null; int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod(); try { httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httppost = new HttpPost(this.endpoint); httppost.setConfig(requestConfig); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(PARAM_NAME_ACTION, new StringBody(CREATE_APPLICATION_ACTION, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APP_CREATION_METHOD, new StringBody(appCreationMethod, ContentType.TEXT_PLAIN)); if (GITHUB.equals(appCreationMethod)) { builder.addPart(PARAM_NAME_GIT_REPO_URL, new StringBody(gitRepoUrl, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_GIT_REPO_BRANCH, new StringBody(gitRepoBranch, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_PROJECT_ROOT, new StringBody(projectRoot, ContentType.TEXT_PLAIN)); } else if (DEFAULT.equals(appCreationMethod)) { builder.addPart(PARAM_NAME_FILE_UPLOAD, new FileBody(uploadArtifact)); builder.addPart(PARAM_NAME_UPLOADED_FILE_NAME, new StringBody(uploadedFileName, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_IS_FILE_ATTACHED, new StringBody(Boolean.TRUE.toString(), ContentType.TEXT_PLAIN));//Setting true to send the file in request } builder.addPart(PARAM_NAME_CONTAINER_SPEC, new StringBody(conSpec, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_NAME, new StringBody(applicationName, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_DESCRIPTION, new StringBody(applicationDescription, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_RUNTIME, new StringBody(runtime, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APP_TYPE_NAME, new StringBody(appTypeName, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APP_CONTEXT, new StringBody(applicationContext, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_REVISION, new StringBody(applicationRevision, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_PROPERTIES, new StringBody(runtimeProperties, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_TAGS, new StringBody(tags, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_IS_NEW_VERSION, new StringBody(Boolean.toString(isNewVersion), ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_SET_DEFAULT_VERSION, new StringBody(Boolean.toString(setDefaultVersion), ContentType.TEXT_PLAIN)); httppost.setEntity(builder.build()); httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE)); response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity()); throw new AppCloudIntegrationTestException("CreateNewApplication failed " + result); } } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) { // In most of the cases, even though connection is timed out, actual activity is completed. // If application is not created, in next test case, it will be identified. log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1); } catch (IOException e) { log.error("Failed to invoke application creation API.", e); throw new AppCloudIntegrationTestException("Failed to invoke application creation API.", e); } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(httpclient); } }
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. j av a 2 s .c om*/ */ @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;//from w w w . java2s. c o 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 {// w w w.j a v 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 {// w ww. j a v a 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 {// ww w . j a v a 2 s . com 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:com.frentix.restapi.RestConnection.java
/** * Attach file to POST request./*w ww . j a v a 2s. c o m*/ * * @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); }