List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:org.hlc.http.resetfull.network.HttpExecutor.java
/** * Do post./*from w ww . j a va2 s . c om*/ * * @param <E> the element type * @param url the url * @param paramter the paramter * @param files the files * @param readTimeout the read timeout * @param result the result * @return the e */ public <E> E doPost(String url, Map<String, Object> paramter, Map<String, File> files, int readTimeout, MessageResolve<E> result) { MultipartEntity multipartEntity = new MultipartEntity(); try { if (paramter != null) { for (String name : paramter.keySet()) { multipartEntity.addPart(name, new StringBody(String.valueOf(paramter.get(name)), Charset.forName(HTTP.UTF_8))); } } if (files != null) { for (String name : files.keySet()) { multipartEntity.addPart(name, new FileBody(files.get(name))); } } } catch (Exception e) { Log.debug(e.getMessage()); result.error(NETWORK_ERROR, DEFUALT_MESSAGE_TYPE, e.getMessage()); return null; } HttpPost httpPost = new HttpPost(url); httpPost.setEntity(multipartEntity); return doExecute(httpPost, readTimeout, result); }
From source file:net.sf.jaceko.mock.it.helper.request.HttpRequestSender.java
private void constructMultipartRequest(HttpEntityEnclosingRequestBase httpRequest, String requestBody, String mediaType, List<RestAttachment> attachments) throws UnsupportedEncodingException { MultipartEntity multipartEntity = new MultipartEntity(); if (requestBody != null) { multipartEntity.addPart("payload", new StringBody(requestBody, mediaType, Charset.forName("UTF-8"))); }// w ww.ja va 2 s . c om int attachmentCount = 0; for (RestAttachment attachment : attachments) { String attachmentName = "attachment" + (++attachmentCount); multipartEntity.addPart(attachmentName, new ByteArrayBody(attachment.getBinaryContent(), attachment.getMediaType(), attachmentName)); } httpRequest.setEntity(multipartEntity); }
From source file:com.reachcall.pretty.http.ProxyServlet.java
@SuppressWarnings("unchecked") private void doMultipart(HttpPost method, HttpServletRequest req) throws ServletException, FileUploadException, UnsupportedEncodingException, IOException { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(TEMP_DIR); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); List<FileItem> fileItems = (List<FileItem>) upload.parseRequest(req); MultipartEntity entity = new MultipartEntity(); for (FileItem fItem : fileItems) { if (fItem.isFormField()) { LOG.log(Level.INFO, "Form field {0}", fItem.getName()); StringBody part = new StringBody(fItem.getFieldName()); entity.addPart(fItem.getFieldName(), part); } else {/*w w w . ja v a 2 s . c o m*/ LOG.log(Level.INFO, "File item {0}", fItem.getName()); InputStreamBody file = new InputStreamBody(fItem.getInputStream(), fItem.getName(), fItem.getContentType()); entity.addPart(fItem.getFieldName(), file); } } method.setEntity(entity); }
From source file:org.jboss.as.test.smoke.mgmt.servermodule.HttpGenericOperationUnitTestCase.java
/** * Execute the post request./*from ww w.ja v a 2s . c o 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:gov.medicaid.screening.dao.impl.BaseDAO.java
/** * Posts the Datagrid form.//from w ww . ja v a 2 s .c o m * * @param hostId * the unique host identifier * @param client * the client to use * @param httppost * the postback resource * @param postFragments * the fragments to include * @param multipartForm * to use multipart or regular form entity * @return the response entity * @throws ClientProtocolException * for protocol connection error * @throws IOException * for IO related errors * @throws ServiceException * if the post execution leads to an error */ protected HttpEntity postForm(String hostId, DefaultHttpClient client, HttpPost httppost, String[][] postFragments, boolean multipartForm) throws ClientProtocolException, IOException, ServiceException { HttpEntity entity = null; if (multipartForm) { MultipartEntity multiPartEntity = new MultipartEntity(); for (String[] params : postFragments) { multiPartEntity.addPart(params[0], new StringBody(params[1])); } entity = multiPartEntity; } else { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); for (String[] params : postFragments) { parameters.add(new BasicNameValuePair(params[0], params[1])); } entity = new UrlEncodedFormEntity(parameters); } httppost.setEntity(entity); HttpResponse postResponse = client.execute(httppost); verifyAndAuditCall(hostId, postResponse); return postResponse.getEntity(); }
From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.services.AuthClientService.java
public boolean createUser(String accountId, UserCreate user, String contentPath) throws TransportException, InvalidDataException, NotFoundException, KurentoCommandException { log.debug("Create user {}", user.getName()); JSONObject object = new JSONObject(); try {//from ww w. j a v a 2 s .c o m object.put(JsonKeys.PASSWORD, user.getPassword()); object.put(JsonKeys.NAME, user.getName()); object.put(JsonKeys.SURNAME, user.getSurname()); object.put(JsonKeys.PHONE, user.getPhone()); object.put(JsonKeys.EMAIL, user.getEmail()); object.put(JsonKeys.PHONE_REGION, ConstantKeys.ES); } catch (JSONException e) { log.debug("Error creating object"); return false; } String json = object.toString(); String charset = HTTP.UTF_8; MultipartEntity mpEntity = new MultipartEntity(); try { mpEntity.addPart(USER_PART_NAME, new StringBody(json, HttpManager.CONTENT_TYPE_APPLICATION_JSON, Charset.forName(charset))); } catch (UnsupportedEncodingException e) { String msg = "Cannot use " + charset + "as entity"; log.error(msg, e); throw new TransportException(msg); } File content = new File(contentPath); mpEntity.addPart(PICTURE_PART_NAME, new FileBody(content, ConstantKeys.TYPE_IMAGE)); HttpResp<Void> resp = HttpManager.sendPostVoid(context, context.getString(R.string.url_create_user, accountId), mpEntity); return resp.getCode() == HttpStatus.SC_CREATED; }
From source file:com.liferay.ide.server.remote.ServerManagerConnection.java
public Object updateApplication(String appName, String absolutePath, IProgressMonitor monitor) throws APIException { try {//from ww w.j a va2 s. com File file = new File(absolutePath); FileBody fileBody = new FileBody(file); MultipartEntity entity = new MultipartEntity(); entity.addPart(file.getName(), fileBody); HttpPut httpPut = new HttpPut(); httpPut.setEntity(entity); Object response = httpJSONAPI(httpPut, _getUpdateURI(appName)); if (response instanceof JSONObject) { JSONObject jsonObject = (JSONObject) response; if (_isSuccess(jsonObject)) { System.out.println("updateApplication: success.\n\n"); } else { if (_isError(jsonObject)) { return jsonObject.getString("error"); } else { return "updateApplication error " + _getDeployURI(appName); } } } httpPut.releaseConnection(); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } return null; }
From source file:com.versacomllc.audit.network.sync.SyncAdapter.java
private String uploadFile(String path) { String downloadPath = Constants.FILE_CONTENT_PATH; if (TextUtils.isEmpty(path)) { Log.d(LOG_TAG, "File path is empty."); return null; }//w ww . j a v a2 s . c o m HttpClient httpclient = new DefaultHttpClient(); try { File file = new File(path); HttpPost httppost = new HttpPost(FILE_UPLOAD_PATH); String mimeType = URLConnection.guessContentTypeFromName(path); FileBody bin = new FileBody(file, mimeType); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(file.getName(), bin); httppost.setEntity(reqEntity); Log.i(TAG, "executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { Log.i(TAG, "Response content length: " + resEntity.getContentLength()); } downloadPath = downloadPath + file.getName(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } return downloadPath; }
From source file:org.eclipse.egit.github.core.service.DownloadService.java
/** * Upload a resource to be available as the download described by the given * resource./* w w w . j a v a 2s . c o m*/ * * @param resource * @param content * @param size * @throws IOException */ public void uploadResource(DownloadResource resource, InputStream content, long size) throws IOException { if (resource == null) throw new IllegalArgumentException("Download resource cannot be null"); //$NON-NLS-1$ if (content == null) throw new IllegalArgumentException("Content input stream cannot be null"); //$NON-NLS-1$ HttpClient client = createDownloadClient(); HttpPost post = new HttpPost(resource.getS3Url()); MultipartEntity entity = new MultipartEntity(); entity.addPart(UPLOAD_KEY, new StringBody(resource.getPath())); entity.addPart(UPLOAD_ACL, new StringBody(resource.getAcl())); entity.addPart(UPLOAD_SUCCESS_ACTION_STATUS, new StringBody(Integer.toString(HttpStatus.SC_CREATED))); entity.addPart(UPLOAD_FILENAME, new StringBody(resource.getName())); entity.addPart(UPLOAD_AWS_ACCESS_KEY_ID, new StringBody(resource.getAccesskeyid())); entity.addPart(UPLOAD_POLICY, new StringBody(resource.getPolicy())); entity.addPart(UPLOAD_SIGNATURE, new StringBody(resource.getSignature())); entity.addPart(HttpHeaders.CONTENT_TYPE, new StringBody(resource.getMimeType())); entity.addPart(UPLOAD_FILE, new SizedInputStreamBody(content, size)); post.setEntity(entity); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_CREATED) throw new IOException("Unexpected response status of " + status); //$NON-NLS-1$ }
From source file:org.openbmap.soapclient.FileUploader.java
/** * @param file/*w w w . j ava 2 s . c o m*/ * @return */ private boolean performUpload(final String file) { // TODO check network state // @see http://developer.android.com/training/basics/network-ops/connecting.html // Adjust HttpClient parameters final HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. //HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT); final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); final HttpPost httppost = new HttpPost(mServer); try { final String authorizationString = "Basic " + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP); httppost.setHeader("Authorization", authorizationString); final MultipartEntity entity = new MultipartEntity(); // TODO we don't need passwords for the new service entity.addPart(LOGIN_FIELD, new StringBody(mUser)); entity.addPart(PASSWORD_FIELD, new StringBody(mPassword)); entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml")); httppost.setEntity(entity); final HttpResponse response = httpclient.execute(httppost); final int reply = response.getStatusLine().getStatusCode(); if (reply == 200) { Log.i(TAG, "Uploaded " + file + ": Server reply " + reply); } else { Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply); } // everything is ok if we receive HTTP 200 // TODO: redirects (301, 302) are NOT handled here // thus if something changes on the server side we're dead here return (reply == HttpStatus.SC_OK); } catch (final ClientProtocolException e) { Log.e(TAG, e.getMessage()); } catch (final IOException e) { Log.e(TAG, "I/O exception on file " + file); } return false; }