List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file)
From source file:org.openurp.thesis.service.impl.CnkiThesisCheckServiceImpl.java
/** * // w w w . ja v a 2s .c o m * * @param author * @param article * @param file * @return * @throws Exception * @see http://pmlc.cnki.net/school/SwfUpload/handlers.js#uploadSuccess */ public boolean upload(String author, String article, File file) { Charset utf8 = Charset.forName("UTF-8"); MultipartEntity reqEntity = new MultipartEntity(); String content = null; try { reqEntity.addPart("JJ", new StringBody("", utf8)); reqEntity.addPart("DW", new StringBody("", utf8)); reqEntity.addPart("FL", new StringBody("", utf8)); reqEntity.addPart("PM", new StringBody(article, utf8)); reqEntity.addPart("ZZ", new StringBody(author, utf8)); reqEntity.addPart("FD", new StringBody(foldId, utf8)); reqEntity.addPart("ASPSESSID", new StringBody(sessionId, utf8)); reqEntity.addPart("Filedata", new FileBody(file)); HttpPost httpost = new HttpPost(uploadUrl); httpost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); content = EntityUtils.toString(entity); EntityUtils.consume(entity); } catch (Exception e) { throw new UnhandledException(e); } logger.debug("upload " + file.getName() + " response is " + content); /* ?200??handlers.jsuploadSuccess */ return StringUtils.trim(content).equals("200"); }
From source file:com.dropbox.client.DropboxClient.java
/** * Put a file in the user's Dropbox.//ww w .j a v a 2 s. c om */ 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<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("file", file_obj.getName())); req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); consumer.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:setiquest.renderer.Utils.java
/** * Send a random BSON file.//from ww w. ja v a 2 s. c om * @return the response from the web server. */ public static String sendRandomBsonFile() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(getOfflineSubjectsURL()); String filename = getRandomFile(getBsonDataDir()); File f = new File(filename); if (!f.exists()) { Log.log("sendRandonBsonFile(): File \"" + filename + "\" does not exists."); return "sendRandonBsonFile(): File \"" + filename + "\" does not exists."; } //Parse info from the name. //Old file = act1207.1.5.bson = actId, pol, subchannel //New file name: act1207.1.0.5.bson = actid, pol, obsType, subchannel int actId = 0; int obsId = 0; int pol = 0; String subchannel = "0"; String shortName = f.getName(); String[] parts = shortName.split("\\."); if (parts.length == 4) //Old name type { actId = Integer.parseInt(parts[0].substring(3)); obsId = 0; //Default to this. pol = Integer.parseInt(parts[1]); subchannel = parts[2]; } else if (parts.length == 5) //New name type { actId = Integer.parseInt(parts[0].substring(3)); pol = Integer.parseInt(parts[1]); obsId = Integer.parseInt(parts[2]); subchannel = parts[3]; } else { Log.log("sendRandonBsonFile(): bad bson file name: " + shortName); return "sendRandonBsonFile(): bad bson file name: " + shortName; } 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()); String sendResult = "Sending: " + shortName + "\n"; 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"; return sendResult; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "undefined"; }
From source file:org.biouno.figshare.FigShareClient.java
/** * Upload a file to an article./*from w w w . j a va 2 s .c o m*/ * * @param articleId article ID * @param file java.io.File file * @return org.biouno.figshare.v1.model.File uploaded file, without the thumbnail URL */ public org.biouno.figshare.v1.model.File uploadFile(long articleId, File file) { HttpClient httpClient = null; try { final String method = String.format("my_data/articles/%d/files", articleId); // create an HTTP request to a protected resource final String url = getURL(endpoint, version, method); // create an HTTP request to a protected resource final HttpPut request = new HttpPut(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ContentBody body = new FileBody(file); FormBodyPart part = FormBodyPartBuilder.create("filedata", body).build(); builder.addPart(part); HttpEntity entity = builder.build(); request.setEntity(entity); // sign the request consumer.sign(request); // send the request httpClient = HttpClientBuilder.create().build(); HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); String json = EntityUtils.toString(responseEntity); org.biouno.figshare.v1.model.File uploadedFile = readFileFromJson(json); return uploadedFile; } catch (OAuthCommunicationException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (OAuthMessageSignerException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (OAuthExpectationFailedException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (ClientProtocolException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (IOException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } }
From source file:com.omt.syncpad.DemoKitActivity.java
private static void postFile() { try {//from w ww . j av a 2 s. c om File f = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + fileName); mf.writeToFile(f); Log.i(TAG, "Midi file generated. Posting file"); HttpPost httppost = new HttpPost(url); MultipartEntity entity = new MultipartEntity(); entity.addPart("filename", new StringBody(fileName)); entity.addPart("fileext", new StringBody(extName)); entity.addPart("upfile", new FileBody(f)); HttpClient httpclient = new DefaultHttpClient(); httppost.setEntity(entity); httpclient.execute(httppost); //HttpResponse response = httpclient.execute(httppost); //Do something with response... Log.i(TAG, "File posted"); } catch (Exception e) { // show error e.printStackTrace(); return; } }
From source file:cc.mincai.android.desecret.storage.dropbox.DropboxClient.java
/** * Put a file in the user's Dropbox.// w ww . j av a 2s . c om */ @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:longism.com.api.APIUtils.java
/** * TODO Function:Upload file then Load json by type POST.<br> * * @param activity - to get context/*from ww w. ja v a 2s. c om*/ * @param action - need authenticate or not, define at top of class * @param data - parameter String * @param files - param file input <key,path of file> * @param url - host of API * @param apiCallBack - call back to handle action when start, finish, success or fail * @date: July 07, 2015 * @author: Nguyen Long */ public static void loadJSONWithUploadFile(final Activity activity, final int action, final HashMap<String, String> data, final HashMap<String, String> files, final String url, final String sUserName, final String sUserPassword, final APICallBack apiCallBack) { activity.runOnUiThread(new Runnable() { @Override public void run() { apiCallBack.uiStart(); } }); new Thread(new Runnable() { @Override public synchronized void run() { try { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME); Charset chars = Charset.forName("UTF-8"); DefaultHttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(url); // DLog.e("Accountant", "url : " + url); MultipartEntity multipartEntity = new MultipartEntity(); if (files != null) { Set<String> set = files.keySet(); for (String key : set) { // DLog.e("Accountant", "param : " + key); File file = new File(files.get(key)); multipartEntity.addPart(key, new FileBody(file)); } } if (data != null) { Set<String> set = data.keySet(); for (String key : set) { // DLog.e("Accountant", "param : " + key); StringBody stringBody = new StringBody(data.get(key), chars); multipartEntity.addPart(key, stringBody); } } post.setEntity(multipartEntity); /** * if need authen then run this code below */ if (action == ACTION_UPLOAD_WITH_AUTH) { setAuthenticate(client, post, sUserName, sUserPassword); } HttpResponse response = null; response = client.execute(post); final StringBuilder builder = new StringBuilder(); if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream inputStream = response.getEntity().getContent(); Scanner scanner = new Scanner(inputStream); while (scanner.hasNext()) { builder.append(scanner.nextLine()); } inputStream.close(); scanner.close(); apiCallBack.success(builder.toString(), 0); } else { apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null" : "" + response.getStatusLine().getStatusCode()); } } catch (final Exception e) { apiCallBack.fail(e.getMessage()); } finally { activity.runOnUiThread(new Runnable() { @Override public void run() { apiCallBack.uiEnd(); } }); } } }).start(); }
From source file:aajavafx.VisitorController.java
@FXML private void handleSave(ActionEvent event) { if (imageFile != null) { String visitorId = visitorIDField.getText(); visitorIDField.clear();//from w w w. j a v a2 s . c o m String firstName = firstNameField.getText(); firstNameField.clear(); String lastName = lastNameField.getText(); lastNameField.clear(); String email = emailField.getText(); emailField.clear(); String phoneNumber = phoneNumberField.getText(); phoneNumberField.clear(); Integer companyId = getCompanyIDFromName(companyBox.getValue().toString()); try { Gson gson = new Gson(); HttpClient httpClient = HttpClientBuilder.create().build(); HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc if (visitorIDField.isEditable()) { //then we are posting a new record HttpEntity = new HttpPost(VisitorsRootURL); //so make a http post object } else { //we are editing a record HttpEntity = new HttpPut(VisitorsRootURL); //so make a http put object } Company company = getCompany(companyId); Visitors visitor = new Visitors(visitorId, firstName, lastName, email, phoneNumber, company); String jsonString = new String(gson.toJson(visitor)); System.out.println("json string: " + jsonString); StringEntity postString = new StringEntity(jsonString); HttpEntity.setEntity(postString); HttpEntity.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(HttpEntity); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 204) { System.out.println("New visitor posted successfully"); } else { System.out.println("Server error: " + response.getStatusLine()); } visitorIDField.setEditable(false); firstNameField.setEditable(false); lastNameField.setEditable(false); emailField.setEditable(false); phoneNumberField.setEditable(false); companyBox.setEditable(false); visitorIDField.clear(); firstNameField.clear(); lastNameField.clear(); emailField.clear(); tableVisitors.setItems(getVisitors()); } catch (UnsupportedEncodingException ex) { System.out.println(ex); } catch (IOException e) { System.out.println(e); } catch (JSONException je) { System.out.println("JSON error: " + je); } FileInputStream fis = null; try { fis = new FileInputStream(imageFile); HttpClient httpClient = HttpClientBuilder.create().build(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(new File(imageFile.getName())); //image should be a String builder.addPart("file", new InputStreamBody(fis, imageFile.getName())); //builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // server back-end URL HttpPost httppost = new HttpPost(postHTML); //MultipartEntity entity = new MultipartEntity(); // set the file input stream and file name as arguments //entity.addPart("file", new InputStreamBody(fis, inFile.getName())); HttpEntity entity = builder.build(); httppost.setEntity(entity); // execute the request HttpResponse response = httpClient.execute(httppost); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println("[" + statusCode + "] " + responseString); } catch (ClientProtocolException e) { System.err.println("Unable to make connection"); e.printStackTrace(); } catch (IOException e) { System.err.println("Unable to read file"); e.printStackTrace(); } finally { try { if (fis != null) fis.close(); } catch (IOException e) { } } } else { errorLabel.setText("Record Not Saved: Please attach a photo for this visitor"); errorLabel.setVisible(true); } }
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java
/** * attach log using run id/*from www . j a va 2 s .co m*/ * * @param token * - token generate using username and password * @param scope * : project:release:cycle * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @return */ public int attachTestLogsUsingRunId(long testCaseRunId, File filePath) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", scope); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
From source file:org.rapidandroid.activity.FormReviewer.java
private void uploadFile(final String filename) { Toast.makeText(getApplicationContext(), FILE_UPLOAD_BEGUN, Toast.LENGTH_LONG).show(); Thread t = new Thread() { @Override/* w ww. j a v a 2 s . c o m*/ public void run() { try { DefaultHttpClient httpclient = new DefaultHttpClient(); File f = new File(filename); HttpPost httpost = new HttpPost("http://192.168.7.127:8160/upload/upload"); MultipartEntity entity = new MultipartEntity(); entity.addPart("myIdentifier", new StringBody("somevalue")); entity.addPart("myFile", new FileBody(f)); httpost.setEntity(entity); HttpResponse response; // Post, check and show the result (not really spectacular, // but works): response = httpclient.execute(httpost); Log.d("httpPost", "Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } success = true; } catch (Exception ex) { Log.d("FormReviewer", "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace()); success = false; } finally { mDebugHandler.post(mFinishUpload); } } }; t.start(); }