List of usage examples for org.apache.http.entity.mime.content InputStreamBody InputStreamBody
public InputStreamBody(final InputStream in, final String filename)
From source file:net.rcarz.jiraclient.RestClient.java
private JSON request(HttpEntityEnclosingRequestBase req, Issue.NewAttachment... attachments) throws RestException, IOException { if (attachments != null) { req.setHeader("X-Atlassian-Token", "nocheck"); MultipartEntity ent = new MultipartEntity(); for (Issue.NewAttachment attachment : attachments) { String filename = attachment.getFilename(); Object content = attachment.getContent(); if (content instanceof byte[]) { ent.addPart("file", new ByteArrayBody((byte[]) content, filename)); } else if (content instanceof InputStream) { ent.addPart("file", new InputStreamBody((InputStream) content, filename)); } else if (content instanceof File) { ent.addPart("file", new FileBody((File) content, filename)); } else if (content == null) { throw new IllegalArgumentException("Missing content for the file " + filename); } else { throw new IllegalArgumentException( "Expected file type byte[], java.io.InputStream or java.io.File but provided " + content.getClass().getName() + " for the file " + filename); }/* w w w . j a v a 2s. c om*/ } req.setEntity(ent); } return request(req); }
From source file:com.box.androidlib.BoxFileUpload.java
/** * Execute a file upload./*from w w w . ja va2s .c o m*/ * * @param action * Set to {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD} or {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or * {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY} * @param sourceInputStream * Input stream targeting the data for the file you wish to create/upload to Box. * @param filename * The desired filename on Box after upload (just the file name, do not include the path) * @param destinationId * If action is {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD}, then this is the folder id where the file will uploaded to. If action is * {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}, then this is the file_id that * is being overwritten, or copied. * @return A FileResponseParser with information about the upload. * @throws IOException * Can be thrown if there is no connection, or if some other connection problem exists. * @throws FileNotFoundException * File being uploaded either doesn't exist, is not a file, or cannot be read * @throws MalformedURLException * Make sure you have specified a valid upload action */ public FileResponseParser execute(final String action, final InputStream sourceInputStream, final String filename, final long destinationId) throws IOException, MalformedURLException, FileNotFoundException { if (!action.equals(Box.UPLOAD_ACTION_UPLOAD) && !action.equals(Box.UPLOAD_ACTION_OVERWRITE) && !action.equals(Box.UPLOAD_ACTION_NEW_COPY)) { throw new MalformedURLException("action must be upload, overwrite or new_copy"); } final Uri.Builder builder = new Uri.Builder(); builder.scheme(BoxConfig.getInstance().getUploadUrlScheme()); builder.encodedAuthority(BoxConfig.getInstance().getUploadUrlAuthority()); builder.path(BoxConfig.getInstance().getUploadUrlPath()); builder.appendPath(action); builder.appendPath(mAuthToken); builder.appendPath(String.valueOf(destinationId)); if (action.equals(Box.UPLOAD_ACTION_OVERWRITE)) { builder.appendQueryParameter("file_name", filename); } else if (action.equals(Box.UPLOAD_ACTION_NEW_COPY)) { builder.appendQueryParameter("new_file_name", filename); } List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters(); if (customQueryParams != null && customQueryParams.size() > 0) { for (BasicNameValuePair param : customQueryParams) { builder.appendQueryParameter(param.getName(), param.getValue()); } } if (BoxConfig.getInstance().getHttpLoggingEnabled()) { // DevUtils.logcat("Uploading : " + filename + " Action= " + action + " DestinionID + " + destinationId); DevUtils.logcat("Upload URL : " + builder.build().toString()); } // Set up post body final HttpPost post = new HttpPost(builder.build().toString()); final MultipartEntityWithProgressListener reqEntity = new MultipartEntityWithProgressListener( HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8)); if (mListener != null && mHandler != null) { reqEntity.setProgressListener(new MultipartEntityWithProgressListener.ProgressListener() { @Override public void onTransferred(final long bytesTransferredCumulative) { mHandler.post(new Runnable() { @Override public void run() { mListener.onProgress(bytesTransferredCumulative); } }); } }); } reqEntity.addPart("file_name", new InputStreamBody(sourceInputStream, filename) { @Override public String getFilename() { return filename; } }); post.setEntity(reqEntity); // Send request final HttpResponse httpResponse; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpProtocolParams.setUserAgent(httpClient.getParams(), BoxConfig.getInstance().getUserAgent()); post.setHeader("Accept-Language", BoxConfig.getInstance().getAcceptLanguage()); try { httpResponse = httpClient.execute(post); } catch (final IOException e) { // Detect if the download was cancelled through thread interrupt. See CountingOutputStream.write() for when this exception is thrown. if (BoxConfig.getInstance().getHttpLoggingEnabled()) { // DevUtils.logcat("IOException Uploading " + filename + " Exception Message: " + e.getMessage() + e.toString()); DevUtils.logcat(" Exception : " + e.toString()); e.printStackTrace(); DevUtils.logcat("Upload URL : " + builder.build().toString()); } if ((e.getMessage() != null && e.getMessage().equals(FileUploadListener.STATUS_CANCELLED)) || Thread.currentThread().isInterrupted()) { final FileResponseParser handler = new FileResponseParser(); handler.setStatus(FileUploadListener.STATUS_CANCELLED); return handler; } else { throw e; } } finally { if (httpClient != null && httpClient.getConnectionManager() != null) { httpClient.getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS); } } if (BoxConfig.getInstance().getHttpLoggingEnabled()) { DevUtils.logcat("HTTP Response Code: " + httpResponse.getStatusLine().getStatusCode()); Header[] headers = httpResponse.getAllHeaders(); // DevUtils.logcat("User-Agent : " + HttpProtocolParams.getUserAgent(httpClient.getParams())); // for (Header header : headers) { // DevUtils.logcat("Response Header: " + header.toString()); // } } // Server returned a 503 Service Unavailable. Usually means a temporary unavailability. if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) { final FileResponseParser handler = new FileResponseParser(); handler.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE); return handler; } String status = null; BoxFile boxFile = null; final InputStream is = httpResponse.getEntity().getContent(); final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); httpResponse.getEntity().consumeContent(); final String xml = sb.toString(); try { final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new ByteArrayInputStream(xml.getBytes())); final Node statusNode = doc.getElementsByTagName("status").item(0); if (statusNode != null) { status = statusNode.getFirstChild().getNodeValue(); } final Element fileEl = (Element) doc.getElementsByTagName("file").item(0); if (fileEl != null) { try { boxFile = Box.getBoxFileClass().newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } for (int i = 0; i < fileEl.getAttributes().getLength(); i++) { boxFile.parseAttribute(fileEl.getAttributes().item(i).getNodeName(), fileEl.getAttributes().item(i).getNodeValue()); } } // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download if (status == null) { status = xml; } } catch (final SAXException e) { // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download status = xml; } catch (final ParserConfigurationException e) { e.printStackTrace(); } final FileResponseParser handler = new FileResponseParser(); handler.setFile(boxFile); handler.setStatus(status); return handler; }
From source file:com.android.flickrbot.FlickrClient.java
/** * Upload a photo to Flickr using the current user credentials. * //from w ww .ja va2s . co m * @param title Photo title * @param description Photo description * @param tags Tags to assign to photo * @param image JPEG object representing the photo */ public void sendPhoto(String title, String description, String tags, InputStream image) throws Exception { // TODO: Verify that we are authorized first. // Build a representation of the parameter list, and use it to sign the request. parameterList params = this.new parameterList(); params.addParameter("api_key", KEY); params.addParameter("auth_token", m_database.getConfigValue(AUTH_TOKEN_NAME)); // Add all of the extra parameters that are passed along with the image. if (title.length() > 0) { params.addParameter("title", title); } if (description.length() > 0) { params.addParameter("description", description); } if (tags.length() > 0) { params.addParameter("tags", tags); } // Build a multipart HTTP request to post to Flickr // Add the text parameters MultipartEntity multipart = params.getMultipartEntity(); // then the photo data multipart.addPart("photo", new InputStreamBody(image, "photo")); // Build the rest of the players HttpClient client = new DefaultHttpClient(); // HttpClient makes requests HttpPost postrequest = new HttpPost(UPLOAD_URL); // HttpPost is the type of request we are making postrequest.setEntity(multipart); HttpResponse response; // HttpResponse holds the return data from HttpPost // TODO: Is this necessary? if (postrequest == null) { // Building the post request has failed throw new Exception("postrequest could not be built"); } // Post the photo. This will throw an exception if the connection fails. response = client.execute(postrequest); System.out.println("POST response code: " + response.getStatusLine().getReasonPhrase()); HttpEntity resp = response.getEntity(); if (resp == null) { throw new Exception("Response entity is empty."); } byte[] b = new byte[999]; resp.getContent().read(b); System.out.println("Response: " + new String(b)); }
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 {/*from w w w .java2 s .c om*/ 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:org.opencastproject.loadtest.impl.IngestJob.java
/** * Use the TrustedHttpClient from matterhorn to ingest the mediapackage. * // w ww .jav a 2 s . c om * @param workingDirectory * The path to the working directory for the LoadTesting. * @param mediaPackageLocation * The location of the mediapackage we want to ingest. */ private void ingestMediaPackageWithJava(String workingDirectory, String mediaPackageLocation, String workflowID) { logger.info("Ingesting recording with HttpTrustedClient: {}", id); try { URL url = new URL(loadTest.getCoreAddress() + "/ingest/addZippedMediaPackage"); File fileDesc = new File(mediaPackageLocation); // Set the file as the body of the request MultipartEntity entities = new MultipartEntity(); // Check to see if the properties have an alternate workflow definition attached String workflowInstance = id; try { entities.addPart("workflowDefinitionId", new StringBody(workflowID, Charset.forName("UTF-8"))); entities.addPart("workflowInstanceId", new StringBody(workflowInstance, Charset.forName("UTF-8"))); entities.addPart(fileDesc.getName(), new InputStreamBody(new FileInputStream(fileDesc), fileDesc.getName())); } catch (FileNotFoundException ex) { logger.error("Could not find zipped mediapackage " + fileDesc.getAbsolutePath()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("This system does not support UTF-8", e); } logger.debug("Ingest URL is " + url.toString()); HttpPost postMethod = new HttpPost(url.toString()); postMethod.setEntity(entities); // Send the file HttpResponse response = null; int retValue = -1; try { logger.debug( "Sending the file " + fileDesc.getAbsolutePath() + " with a size of " + fileDesc.length()); response = client.execute(postMethod); } catch (TrustedHttpClientException e) { logger.error("Unable to ingest recording {}, message reads: {}.", id, e.getMessage()); } catch (NullPointerException e) { logger.error("Unable to ingest recording {}, null pointer exception!", id); } finally { if (response != null) { retValue = response.getStatusLine().getStatusCode(); client.close(response); } else { retValue = -1; } } if (retValue == HttpURLConnection.HTTP_OK) { logger.info(id + " successfully ingested."); } else { logger.info(id + " ingest failed with return code " + retValue + " and status line " + response.getStatusLine().toString()); } } catch (MalformedURLException e) { logger.error("Malformed URL for ingest target \"" + loadTest.getCoreAddress() + "/ingest/addZippedMediaPackage\""); } }
From source file:se.vgregion.service.barium.BariumRestClientImpl.java
/** * Do post multipart./* w w w . j ava2s . c o m*/ * * @param endpoint the endpoint * @param fileName the file name * @param inputStream the input stream * @return the string * @throws BariumException the barium exception */ String doPostMultipart(String endpoint, String fileName, InputStream inputStream) throws BariumException { DefaultHttpClient httpClient = new DefaultHttpClient(); //httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("140.166.209.205", 8888)); HttpPost httpPost = new HttpPost(this.apiLocation + endpoint); if (ticket != null) { httpPost.setHeader("ticket", ticket); } else { this.connect(); httpPost.setHeader("ticket", ticket); } try { ContentBody contentBody = new InputStreamBody(inputStream, fileName); // Must use HttpMultipartMode.BROWSER_COMPATIBLE in order to use UTF-8 instead of US_ASCII to handle special // characters. MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")) { // Due to a bug in Barium we must not append the charset directive to the content-type header since // nothing is created in Barium if doing so. // todo Try skipping this when we use Barium Live? @Override protected String generateContentType(final String boundary, final Charset charset) { StringBuilder buffer = new StringBuilder(); buffer.append("multipart/form-data; boundary="); buffer.append(boundary); // Comment out this /*if (charset != null) { buffer.append("; charset="); buffer.append(charset.name()); }*/ return buffer.toString(); } }; multipartEntity.addPart("Data", contentBody); httpPost.setEntity(multipartEntity); HttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new BariumException( "Failed to post multipart. Reason: " + response.getStatusLine().getReasonPhrase()); } InputStream content = response.getEntity().getContent(); return toString(content); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (ClientProtocolException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.secdec.codedx.api.client.CodeDxClient.java
/** * Kicks off a CodeDx analysis run on a specified project * * @return A StartAnalysisResponse object * @param projectId The project ID/*from www . j a v a 2 s. co m*/ * @param artifacts An array of streams to send over as analysis artifacts * @throws ClientProtocolException * @throws IOException * @throws CodeDxClientException * */ public StartAnalysisResponse startAnalysis(int projectId, InputStream[] artifacts) throws ClientProtocolException, IOException, CodeDxClientException { HttpPost postRequest = new HttpPost(url + "projects/" + projectId + "/analysis"); postRequest.addHeader(KEY_HEADER, key); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (InputStream artifact : artifacts) { builder.addPart("file[]", new InputStreamBody(artifact, "file[]")); } HttpEntity entity = builder.build(); postRequest.setEntity(entity); HttpResponse response = httpClient.execute(postRequest); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 202) { throw new CodeDxClientException( "Failed to start analysis. " + IOUtils.toString(response.getEntity().getContent()), responseCode); } String data = IOUtils.toString(response.getEntity().getContent()); return gson.<StartAnalysisResponse>fromJson(data, new TypeToken<StartAnalysisResponse>() { }.getType()); }
From source file:net.zypr.api.Protocol.java
public JSONObject doStreamPost(APIVerbs apiVerb, Hashtable<String, String> urlParameters, Hashtable<String, String> postParameters, InputStream inputStream) throws APICommunicationException, APIProtocolException { if (!_apiEntity.equalsIgnoreCase("voice")) Session.getInstance().addActiveRequestCount(); long t1 = System.currentTimeMillis(); JSONObject jsonObject = null;/*ww w. j ava 2 s . c o m*/ JSONParser jsonParser = new JSONParser(); try { DefaultHttpClient httpclient = getHTTPClient(); HttpPost httpPost = new HttpPost(buildURL(apiVerb, urlParameters)); HttpProtocolParams.setUseExpectContinue(httpPost.getParams(), false); MultipartEntity multipartEntity = new MultipartEntity(); if (postParameters != null) for (Enumeration enumeration = postParameters.keys(); enumeration.hasMoreElements();) { String key = enumeration.nextElement().toString(); String value = postParameters.get(key); multipartEntity.addPart(key, new StringBody(value)); Debug.print("HTTP POST : " + key + "=" + value); } if (inputStream != null) { InputStreamBody inputStreamBody = new InputStreamBody(inputStream, "binary/octet-stream"); multipartEntity.addPart("audio", inputStreamBody); } httpPost.setEntity(multipartEntity); HttpResponse httpResponse = httpclient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() != 200) throw new APICommunicationException("HTTP Error " + httpResponse.getStatusLine().getStatusCode() + " - " + httpResponse.getStatusLine().getReasonPhrase()); HttpEntity httpEntity = httpResponse.getEntity(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent())); jsonObject = (JSONObject) jsonParser.parse(bufferedReader); bufferedReader.close(); httpclient.getConnectionManager().shutdown(); } catch (ParseException parseException) { throw new APIProtocolException(parseException); } catch (IOException ioException) { throw new APICommunicationException(ioException); } catch (ClassCastException classCastException) { throw new APIProtocolException(classCastException); } finally { if (!_apiEntity.equalsIgnoreCase("voice")) Session.getInstance().removeActiveRequestCount(); long t2 = System.currentTimeMillis(); Debug.print(buildURL(apiVerb, urlParameters) + " : " + t1 + "-" + t2 + "=" + (t2 - t1) + " : " + jsonObject); } return (jsonObject); }
From source file:aajavafx.VisitorController.java
@FXML private void handleSave(ActionEvent event) { if (imageFile != null) { String visitorId = visitorIDField.getText(); visitorIDField.clear();//from w ww. ja va 2 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); } }