List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file)
From source file:ca.sqlpower.enterprise.ClientSideSessionUtils.java
public static ProjectLocation uploadProject(SPServerInfo serviceInfo, String name, File project, UserPrompterFactory session, CookieStore cookieStore) throws URISyntaxException, ClientProtocolException, IOException, JSONException { HttpClient httpClient = ClientSideSessionUtils.createHttpClient(serviceInfo, cookieStore); try {/*ww w . j a v a2 s . c o m*/ MultipartEntity entity = new MultipartEntity(); ContentBody fileBody = new FileBody(project); ContentBody nameBody = new StringBody(name); entity.addPart("file", fileBody); entity.addPart("name", nameBody); HttpPost request = new HttpPost(ClientSideSessionUtils.getServerURI(serviceInfo, "/" + ClientSideSessionUtils.REST_TAG + "/jcr", "name=" + name)); request.setEntity(entity); JSONMessage message = httpClient.execute(request, new JSONResponseHandler()); JSONObject response = new JSONObject(message.getBody()); return new ProjectLocation(response.getString("uuid"), response.getString("name"), serviceInfo); } catch (AccessDeniedException e) { session.createUserPrompter("You do not have sufficient privileges to create a new workspace.", UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser(""); return null; } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:de.tu_dortmund.ub.data.dswarm.Init.java
/** * uploads a file and creates a data resource with it * * @param filename//ww w. j a v a 2 s. c o m * @param name * @param description * @return responseJson * @throws Exception */ private String uploadFileAndCreateResource(final String filename, final String name, final String description, final String serviceName, final String engineDswarmAPI) throws Exception { try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { final HttpPost httpPost = new HttpPost(engineDswarmAPI + DswarmBackendStatics.RESOURCES_ENDPOINT); final File file1 = new File(filename); final FileBody fileBody = new FileBody(file1); final StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN); final StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN); final HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart(DswarmBackendStatics.NAME_IDENTIFIER, stringBodyForName) .addPart(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, stringBodyForDescription) .addPart(FILE_IDENTIFIER, fileBody).build(); httpPost.setEntity(reqEntity); LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpPost.getRequestLine())); try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); final HttpEntity httpEntity = httpResponse.getEntity(); final String message = String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase()); switch (statusCode) { case 201: { LOG.info(message); final StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, APIStatics.UTF_8); final String responseJson = writer.toString(); writer.flush(); writer.close(); LOG.debug(String.format("[%s][%d] responseJson : %s", serviceName, cnt, responseJson)); return responseJson; } default: { LOG.error(message); EntityUtils.consume(httpEntity); throw new Exception("something went wrong at resource upload: " + message); } } } } }
From source file:co.aurasphere.botmill.fb.internal.util.network.FbBotMillNetworkController.java
/** * POSTs a message as a JSON string to Facebook. * * @param recipient// ww w .ja v a 2 s . c om * the recipient * @param type * the type * @param file * the file */ public static void postFormDataMessage(String recipient, AttachmentType type, File file) { String pageToken = FbBotMillContext.getInstance().getPageToken(); // If the page token is invalid, returns. if (!validatePageToken(pageToken)) { return; } // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO) HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken); FileBody filedata = new FileBody(file); StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}", ContentType.MULTIPART_FORM_DATA); StringBody messagePart = new StringBody( "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}", ContentType.MULTIPART_FORM_DATA); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.STRICT); builder.addPart("recipient", recipientPart); builder.addPart("message", messagePart); // builder.addPart("filedata", filedata); builder.addBinaryBody("filedata", file); builder.setContentType(ContentType.MULTIPART_FORM_DATA); // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW"); HttpEntity entity = builder.build(); post.setEntity(entity); // Logs the raw JSON for debug purposes. BufferedReader br; // post.addHeader("Content-Type", "multipart/form-data"); try { // br = new BufferedReader(new InputStreamReader( // ()))); Header[] allHeaders = post.getAllHeaders(); for (Header h : allHeaders) { logger.debug("Header {} -> {}", h.getName(), h.getValue()); } // String output = br.readLine(); } catch (Exception e) { e.printStackTrace(); } // postInternal(post); }
From source file:com.fhc25.percepcion.osiris.mapviewer.common.restutils.RestClient.java
/** * Executes the requests.//from w ww . j a va 2 s .c o m * * @param method the type of method (POST, GET, DELETE, PUT). * @param url the url of the request. * @param headers the headers to include. * @param listener a listener for callbacks. * @throws Exception */ public static void Execute(final File file, final RequestMethod method, final String url, final ArrayList<NameValuePair> headers, final RestListener listener) throws Exception { new Thread() { @Override public void run() { switch (method) { case GET: // Do nothing break; case POST: { HttpPost request = new HttpPost(url); // add headers if (headers != null) { for (NameValuePair h : headers) request.addHeader(h.getName(), h.getValue()); } // code file MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); Log.d(TAG, "UPLOAD: file length = " + file.length()); Log.d(TAG, "UPLOAD: file exist = " + file.exists()); FileBody bodyPart = new FileBody(file); entity.addPart("file", bodyPart); request.setEntity(entity); Log.i(TAG, "Request with File:" + request.getEntity()); executeRequest(request, url, listener); } break; case PUT: { HttpPut request = new HttpPut(url); // add headers if (headers != null) { for (NameValuePair h : headers) request.addHeader(h.getName(), h.getValue()); } // code file MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); Log.d(TAG, "UPLOAD: file length = " + file.length()); Log.d(TAG, "UPLOAD: file exist = " + file.exists()); FileBody bodyPart = new FileBody(file); entity.addPart("file", bodyPart); request.setEntity(entity); Log.v(TAG, "Request " + request.toString()); executeRequest(request, url, listener); } break; case DELETE: // Do nothing break; } // switch end } }.start(); }
From source file:ro.teodorbaciu.commons.client.ws.BaseWsMethods.java
/** * Handles the communication details with the server. * //from www . j ava2 s . com * @param moduleName the name of the module * @param op the operation to call * @param targetUrl the url to post the call * @param wsParamsList contains the parameters to submit for the webservice call * @return the result of the call * @throws Exception if an error occurs */ private String callServerMultipartPost(String moduleName, String op, String targetUrl, List<NameValuePair> wsParamsList, File fileToUpload, WriteListener writeListener) throws AuthorizationRequiredException, OperationForbiddenException, UnsupportedEncodingException, ClientProtocolException, IOException { if (currentRequest != null) { throw new RuntimeException("Another webservice request is still executing !"); } MultipartEntity reqEntity = null; if (writeListener != null) { reqEntity = new MultipartEntityWithProgressMonitoring(writeListener); } else { reqEntity = new MultipartEntity(); } for (NameValuePair pair : wsParamsList) { reqEntity.addPart(pair.getName(), new StringBody(pair.getValue())); } reqEntity.addPart("data", new FileBody(fileToUpload)); String postUrl = targetUrl + "?module=" + moduleName + "&op=" + op; HttpPost post = new HttpPost(postUrl); post.setEntity(reqEntity); return processServerPost(post); }
From source file:org.kuali.ole.docstore.common.client.DocstoreRestClient.java
private RestResponse postMultiPartRequest(File bagitFile) { HttpClient httpclient = new DefaultHttpClient(); FileBody uploadFilePart = new FileBody(bagitFile); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("upload-file", uploadFilePart); HttpPost httpPost = new HttpPost(DOCSTORE_URL + LICENSES_URL); httpPost.setEntity(reqEntity);//from w w w. ja v a 2s. c om httpPost.addHeader("multipart/form-data", "text/xml"); RestResponse restResponse = new RestResponse(); try { EntityUtils.consume(reqEntity); HttpResponse response = httpclient.execute(httpPost); restResponse.setResponse(response); restResponse.setResponseBody(getEncodeEntityValue(response.getEntity())); } catch (Exception e) { e.printStackTrace(); } return restResponse; }
From source file:setiquest.renderer.Utils.java
/** * Send a BSON file./*from w ww.j a v a 2 s . c o m*/ * @param filename the full path to the BSON file. * @param actId the activity Id. * @param obsId the observation Id. * @param pol the POL of thedata. * @param subchannel the subchannel of the data. */ public static String sendBSONFile(String filename, int actId, int obsId, int pol, String subchannel) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Utils.getSubjectsURL()); Log.log("Sending " + filename + ", Act:" + actId + ", Obs type:" + obsId + ", Pol" + pol + ", subchannel:" + subchannel); FileBody bin = new FileBody(new File(filename)); try { StringBody comment = new StringBody("Filename: " + filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("type", new StringBody("data/bson")); reqEntity.addPart("subject[activity_id]", new StringBody("" + actId)); reqEntity.addPart("subject[observation_id]", new StringBody("" + obsId)); reqEntity.addPart("subject[pol]", new StringBody("" + pol)); reqEntity.addPart("subject[subchannel]", new StringBody("" + subchannel)); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); Log.log(response.toString()); return response.toString(); /* sendResult = "subject[activity_id]: " + actId + "\n"; sendResult += "subject[observation_id]: " + obsId + "\n"; sendResult += "subject[pol]: " + pol + "\n"; sendResult += "subject[subchannel]: " + subchannel + "\n"; sendResult += response.toString() + "|\n"; */ } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "ERROR"; }
From source file:gov.nist.appvet.toolmgr.ToolServiceAdapter.java
public MultipartEntity getMultipartEntity() { final MultipartEntity entity = new MultipartEntity(); File apkFile = null;//from w w w .ja va 2 s . c o m FileBody fileBody = null; try { String fileUploadParamName = null; // Add parameter name-value pairs if (formParameterNames != null) { for (int i = 0; i < formParameterNames.size(); i++) { final String paramName = formParameterNames.get(i); String paramValue = formParameterValues.get(i); if (paramValue.equals("APP_FILE")) { fileUploadParamName = paramName; } else { if (paramValue.equals("APPVET_DEFINED")) { if (paramName.equals("appid")) { appInfo.log.debug("Found " + paramName + " = " + "'APPVET_DEFINED' for tool '" + id + "'. Setting to appid = '" + appInfo.appId + "'"); paramValue = appInfo.appId; } else { appInfo.log.error("Found " + paramName + " = " + "'APPVET_DEFINED' for tool '" + id + "' but no actual value is set by AppVet. Aborting."); return null; } } if ((paramName == null) || paramName.isEmpty()) { appInfo.log.warn("Param name is null or empty " + "for tool '" + name + "'"); } else if ((paramValue == null) || paramValue.isEmpty()) { appInfo.log.warn("Param value is null or empty " + "for tool '" + name + "'"); } StringBody partValue = new StringBody(paramValue, Charset.forName("UTF-8")); entity.addPart(paramName, partValue); partValue = null; } } } final String apkFilePath = appInfo.getIdPath() + "/" + appInfo.fileName; appInfo.log.debug("Sending file: " + apkFilePath); apkFile = new File(apkFilePath); fileBody = new FileBody(apkFile); entity.addPart(fileUploadParamName, fileBody); return entity; } catch (final UnsupportedEncodingException e) { appInfo.log.error(e.getMessage()); return null; } }
From source file:gov.nist.appvet.tool.AsynchronousService.java
public void sendReport(String appid, String toolrisk, String reportPath) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 30000); HttpConnectionParams.setSoTimeout(httpParameters, 1200000); HttpClient httpclient = new DefaultHttpClient(httpParameters); httpclient = SSLWrapper.wrapClient(httpclient); try {/* w w w . ja v a 2 s .c o m*/ // To send reports back to AppVet, the following parameters must // be sent: // * command: SUBMIT_REPORT // * username: AppVet username // * password: AppVet password // * appid: The app ID // * toolid: The ID of this tool // * toolrisk: The risk assessment (PASS,FAIL,WARNING,ERROR) // * file: The report file. MultipartEntity entity = new MultipartEntity(); entity.addPart("command", new StringBody("SUBMIT_REPORT", Charset.forName("UTF-8"))); entity.addPart("username", new StringBody(Properties.appVetUsername, Charset.forName("UTF-8"))); entity.addPart("password", new StringBody(Properties.appVetPassword, Charset.forName("UTF-8"))); entity.addPart("appid", new StringBody(appid, Charset.forName("UTF-8"))); entity.addPart("toolid", new StringBody(Properties.toolId, Charset.forName("UTF-8"))); entity.addPart("toolrisk", new StringBody(toolrisk, Charset.forName("UTF-8"))); File report = new File(reportPath); FileBody fileBody = new FileBody(report); entity.addPart("file", fileBody); HttpPost httpPost = new HttpPost(Properties.appVetURL); httpPost.setEntity(entity); log.debug("Sending report to AppVet"); // Send the app to the tool final HttpResponse response = httpclient.execute(httpPost); httpPost = null; log.debug("Received: " + response.getStatusLine()); } catch (Exception e) { e.printStackTrace(); } }