List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file)
From source file:mydropbox.Client.java
public boolean sendFile(String fileName) throws IOException { int status = 0; Timestamp temp_timestamp = new Timestamp(System.currentTimeMillis()); long timestamp = temp_timestamp.getTime(); File file = new File("./files/" + fileName); HttpPost httpPost = new HttpPost(this.host + "upload" + '/' + timestamp); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart(file.getName(), cbFile); httpPost.setEntity(mpEntity);/*from w ww .j av a 2s. c om*/ System.out.println("executing request " + httpPost.getRequestLine()); HttpResponse response; try { httpPost.setHeader("User-Agent", USER_AGENT); httpPost.setHeader("MyDropBox", "MyDropBox"); response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); status = response.getStatusLine().getStatusCode(); System.out.println("Response Code : " + status); System.out.println(EntityUtils.toString(resEntity)); } catch (Exception ex) { ex.printStackTrace(); } finally { setTimeStamp(timestamp); } if (status >= 200 && status < 300) return true; else return false; }
From source file:com.klinker.android.twitter.utils.api_helper.TwitPicHelper.java
private TwitPicStatus uploadToTwitPic() { try {//from w ww . j a v a2 s.c om HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(POST_URL); post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER); post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter)); if (file == null) { // only the input stream was sent, so we need to convert it to a file Log.v("talon_twitpic", "converting to file from input stream"); String filePath = saveStreamTemp(stream); file = new File(filePath); } else { Log.v("talon_twitpic", "already have the file, going right to send it"); } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("key", new StringBody(TWITPIC_API_KEY)); entity.addPart("media", new FileBody(file)); entity.addPart("message", new StringBody(message)); Log.v("talon_twitpic", "uploading now"); post.setEntity(entity); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line; String url = ""; StringBuilder builder = new StringBuilder(); while ((line = rd.readLine()) != null) { Log.v("talon_twitpic", line); builder.append(line); } try { // there is only going to be one thing returned ever JSONObject jsonObject = new JSONObject(builder.toString()); url = jsonObject.getString("url"); } catch (Exception e) { e.printStackTrace(); } Log.v("talon_twitpic", "url: " + url); Log.v("talon_twitpic", "message: " + message); return new TwitPicStatus(message, url); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.openml.knime.OpenMLWebservice.java
/** * Upload an implementation.// w ww . ja v a 2s.c o m * * * @param description Implementation description file * @param workflow Workflow file * @param user Name of the user * @param password Password of the user * @return Response from the server * @throws Exception If communication failed */ public static String sendImplementation(final File description, final File workflow, final String user, final String password) throws Exception { String result = ""; DefaultHttpClient httpclient = new DefaultHttpClient(); try { Credentials credentials = new UsernamePasswordCredentials(user, password); AuthScope scope = new AuthScope(new URI(WEBSERVICEURL).getHost(), 80); httpclient.getCredentialsProvider().setCredentials(scope, credentials); String url = WEBSERVICEURL + "?f=openml.implementation.upload"; HttpPost httppost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntity(); FileBody descBin = new FileBody(description); reqEntity.addPart("description", descBin); FileBody workflowBin = new FileBody(workflow); reqEntity.addPart("source", workflowBin); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() < 200) { throw new Exception(response.getStatusLine().getReasonPhrase()); } if (resEntity != null) { result = convertStreamToString(resEntity.getContent()); } ErrorDocument errorDoc = null; try { errorDoc = ErrorDocument.Factory.parse(result); } catch (Exception e) { // no error XML should mean no error } if (errorDoc != null && errorDoc.validate()) { ErrorDocument.Error error = errorDoc.getError(); String errorMessage = error.getCode() + " : " + error.getMessage(); if (error.isSetAdditionalInformation()) { errorMessage += " : " + error.getAdditionalInformation(); } throw new Exception(errorMessage); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { // ignore } } return result; }
From source file:holon.util.HTTP.java
public static Payload form(Map<String, Object> fields) { return () -> { MultipartEntity entity = new MultipartEntity(); for (Map.Entry<String, Object> entry : fields.entrySet()) { if (entry.getValue() instanceof File) { entity.addPart(entry.getKey(), new FileBody((File) entry.getValue())); } else { try { entity.addPart(entry.getKey(), new StringBody((String) entry.getValue())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }//from ww w . j a va 2 s .c o m } } return entity; }; }
From source file:org.dataconservancy.ui.it.support.MetadataFileRequest.java
public HttpPost asHttpPost() { String depositUrl = urlConfig.getMetadataFileUrl().toString(); HttpPost post = new HttpPost(depositUrl); MultipartEntity entity = new MultipartEntity(); try {/*from ww w. ja v a 2 s . c o m*/ entity.addPart("parentID", new StringBody(parentId, Charset.forName("UTF-8"))); if (name != null && !name.isEmpty()) { entity.addPart("metadataFile.name", new StringBody(name, Charset.forName("UTF-8"))); } if (metadataFormat != null && !metadataFormat.isEmpty()) { entity.addPart("metadataFile.metadataFormatId", new StringBody(metadataFormat, Charset.forName("UTF-8"))); } if (id != null && !id.isEmpty()) { entity.addPart("metadataFileID", new StringBody(id, Charset.forName("UTF-8"))); } if (isCollection) { entity.addPart("redirectUrl", new StringBody("viewCollectionDetails", Charset.forName("UTF-8"))); } entity.addPart(event, new StringBody(event, Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } if (fileToDeposit != null) { FileBody fileBody = new FileBody(fileToDeposit); entity.addPart("uploadedFile", fileBody); post.setEntity(entity); } return post; }
From source file:com.welocalize.dispatcherMW.client.Main.java
public static String uploadXLF(String p_fileName, String p_securityCode) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(getFunctinURL(TYPE_UPLOAD, p_securityCode, null)); try {/*from www. j a v a2 s . c om*/ HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("fileName", new StringBody(p_fileName, ContentType.create("text/plain", Consts.UTF_8))) .addPart("file", new FileBody(new File(p_fileName))).build(); httpPost.setEntity(reqEntity); // send the http request and get the http response HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); String jobID = null; String msg = EntityUtils.toString(resEntity); if (msg.contains("\"jobID\":\"")) { int startIndex = msg.indexOf("\"jobID\":\""); jobID = msg.substring(startIndex + 9, msg.indexOf(",", startIndex) - 1); System.out.println("Create Job: " + jobID + ", wtih file:" + p_fileName); return jobID; } System.out.println(msg); return jobID; } catch (Exception e) { System.out.println("testHTTPClient error. " + e); } finally { httpPost.releaseConnection(); } return null; }
From source file:com.testmax.util.FileUtility.java
public void fileUpload(String url, String filename) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); FileBody fileContent = new FileBody(new File(filename)); try {// w w w. j a v a 2 s . c om StringBody comment = new StringBody("Filename: " + filename); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", fileContent); httppost.setEntity(reqEntity); HttpResponse response = null; try { response = httpclient.execute(httppost); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpEntity resEntity = response.getEntity(); }
From source file:cn.net_show.doctor.activity.AuthActivity.java
private void auth(final String key) { new Thread() { public void run() { isUpload = true;//from w w w . java 2 s. c om Message msg = mHandler.obtainMessage(); msg.what = 1; ArrayList<ContentPart> list = new ArrayList<>(); File file = SimpleUtils.Uri2File(AuthActivity.this, uri); if (file == null || !file.exists()) { Log.e("upload", "file path error!"); isUpload = false; msg.obj = "?"; mHandler.sendMessage(msg); return; } ContentPart part = new ContentPart(key, new FileBody(file)); list.add(part); // part = new ContentPart("license", new FileBody(null)); // list.add(part); String url = MyApplication.ServerUrl + "/doctor/level/authen?uid=" + app.Doctor.getDoctorID() + "&sessionkey=" + app.Doctor.getSessionKey(); String result = httpUtil.mulitiPost(url, list); Logger.e("upload", result + ""); if (result == null) { msg.obj = "?"; } else { if (jUtils.isSuccess(result)) { msg.obj = "??"; } else { msg.obj = "?"; } } mHandler.sendMessage(msg); isUpload = false; } }.start(); }
From source file:dk.kasperbaago.JSONHandler.JSONHandler.java
public String getURL() { //Making a HTTP client HttpClient client = new DefaultHttpClient(); //Declaring HTTP response HttpResponse response = null;//from w w w.ja v a 2 s. com String myReturn = null; try { //Making a HTTP getRequest or post request if (method == "get") { String parms = ""; if (this.parameters.size() > 0) { parms = "?"; parms += URLEncodedUtils.format(this.parameters, "utf-8"); } Log.i("parm", parms); Log.i("URL", this.url + parms); HttpGet getUrl = new HttpGet(this.url + parms); //Executing the request response = client.execute(getUrl); } else if (method == "post") { HttpPost getUrl = new HttpPost(this.url); //Sets parameters to add MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int i = 0; i < this.parameters.size(); i++) { if (this.parameters.get(i).getName().equalsIgnoreCase(fileField)) { entity.addPart(parameters.get(i).getName(), new FileBody(new File(parameters.get(i).getValue()))); } else { entity.addPart(parameters.get(i).getName(), new StringBody(parameters.get(i).getName())); } } getUrl.setEntity(entity); //Executing the request response = client.execute(getUrl); } else { return "false"; } //Returns the data HttpEntity content = response.getEntity(); InputStream mainContent = content.getContent(); myReturn = this.convertToString(mainContent); this.HTML = myReturn; Log.i("Result", myReturn); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return myReturn; }
From source file:org.wso2.security.tools.scanner.dependency.js.ticketcreator.JIRARestClient.java
/** * Invoke put method to attach file for particular ticket. * * @param auth credentials info of JIRA. * @param url url to be invoked./*from ww w . j av a2s. co m*/ * @param path path of the file to be attached. * @throws TicketCreatorException Exception occurred while attaching the file with ticket. */ public void invokePutMethodWithFile(String auth, String url, String path) throws TicketCreatorException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); httppost.setHeader("X-Atlassian-Token", "nocheck"); httppost.setHeader("Authorization", "Basic " + auth); File fileToUpload = new File(path); FileBody fileBody = new FileBody(fileToUpload); HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build(); httppost.setEntity(entity); CloseableHttpResponse response; try { response = httpclient.execute(httppost); log.info("[JS_SEC_DAILY_SCAN] File attached with ticket : " + response.toString()); } catch (IOException e) { throw new TicketCreatorException( "File upload failed while attaching the scan report with issue ticket: " + path, e); } finally { try { httpclient.close(); } catch (IOException e) { log.error("Exception occurred while closing the http connection", e); } } }