List of usage examples for java.net URLConnection guessContentTypeFromName
public static String guessContentTypeFromName(String fname)
From source file:org.LinuxdistroCommunity.android.client.PostEntry.java
/** * Fire the task to post the media entry. The media information is encoded * in Bundles. Each Bundle MUST contain the KEY_FILE_PATH pointing to the * resource. Bundles MAY contain KEY_TITLE and KEY_DESCRIPTION for passing * additional metadata.//w w w . j a v a 2s .c om * */ @Override protected JSONObject doInBackground(Bundle... mediaInfoBundles) { Bundle mediaInfo = mediaInfoBundles[0]; HttpURLConnection connection = null; Uri.Builder uri_builder = Uri.parse(mServer + API_BASE + API_POST_ENTRY).buildUpon(); uri_builder.appendQueryParameter(PARAM_ACCESS_TOKEN, mToken); String charset = "UTF-8"; File binaryFile = new File(mediaInfo.getString(KEY_FILE_PATH)); // Semi-random value to act as the boundary String boundary = Long.toHexString(System.currentTimeMillis()); String CRLF = "\r\n"; // Line separator required by multipart/form-data. PrintWriter writer = null; try { URL url = new URL(uri_builder.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream output = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important! // Send metadata if (mediaInfo.containsKey(KEY_TITLE)) { writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"title\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF); writer.append(mediaInfo.getString(KEY_TITLE)).append(CRLF).flush(); } if (mediaInfo.containsKey(KEY_DESCRIPTION)) { writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"description\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF); writer.append(mediaInfo.getString(KEY_DESCRIPTION)).append(CRLF).flush(); } // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append( "Content-Disposition: form-data; name=\"file\"; filename=\"" + binaryFile.getName() + "\"") .append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())) .append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); InputStream input = null; try { input = new FileInputStream(binaryFile); byte[] buffer = new byte[1024]; for (int length = 0; (length = input.read(buffer)) > 0;) { output.write(buffer, 0, length); } output.flush(); // Important! Output cannot be closed. Close of // writer will close output as well. } finally { if (input != null) try { input.close(); } catch (IOException logOrIgnore) { } } writer.append(CRLF).flush(); // CRLF is important! It indicates end // of binary boundary. // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF); writer.close(); // read the response int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Log.d(TAG, Integer.toString(serverResponseCode)); Log.d(TAG, serverResponseMessage); InputStream is = connection.getInputStream(); // parse token_response as JSON to get the token out String str_response = NetworkUtilities.readStreamToString(is); Log.d(TAG, str_response); JSONObject response = new JSONObject(str_response); return response; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // if (writer != null) writer.close(); } return null; }
From source file:count.ly.messaging.ConnectionProcessor.java
URLConnection urlConnectionForEventData(final String eventData) throws IOException { String urlStr = serverURL_ + "/i?"; if (!eventData.contains("&crash=")) urlStr += eventData;/*from w w w . j a v a2s. com*/ final URL url = new URL(urlStr); final HttpURLConnection conn; if (Countly.publicKeyPinCertificates == null) { conn = (HttpURLConnection) url.openConnection(); } else { HttpsURLConnection c = (HttpsURLConnection) url.openConnection(); c.setSSLSocketFactory(sslContext_.getSocketFactory()); conn = c; } conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS); conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS); conn.setUseCaches(false); conn.setDoInput(true); String picturePath = UserData.getPicturePathFromQuery(url); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Got picturePath: " + picturePath); } if (!picturePath.equals("")) { //Uploading files: //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests File binaryFile = new File(picturePath); conn.setDoOutput(true); // Just generate some unique random value. String boundary = Long.toHexString(System.currentTimeMillis()); // Line separator required by multipart/form-data. String CRLF = "\r\n"; String charset = "UTF-8"; conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream output = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())) .append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); FileInputStream fileInputStream = new FileInputStream(binaryFile); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1) { output.write(buffer, 0, len); } output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. fileInputStream.close(); // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); } else if (eventData.contains("&crash=")) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Using post because of crash"); } conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(eventData); writer.flush(); writer.close(); os.close(); } else { conn.setDoOutput(false); } return conn; }
From source file:com.t3.persistence.FileUtil.java
/** * Given a URL this method tries to figure out what the content type might be based * only on the filename extension.//from w ww . j a v a 2s . c o m * * @param url the URL to check * @return a <code>String</code> representing the content type name */ public static String getContentType(URL url) { String type = ""; type = URLConnection.guessContentTypeFromName(url.getPath()); if (log.isDebugEnabled()) log.debug("result from guessContentTypeFromName(" + url.getPath() + ") is " + type); return type; }
From source file:com.example.dlp.Inspect.java
private static void inspectFile(String filePath, Likelihood minLikelihood, int maxFindings, List<InfoType> infoTypes, boolean includeQuote) { // [START dlp_inspect_file] // Instantiates a client try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) { // The path to a local file to inspect. Can be a text, JPG, or PNG file. // fileName = 'path/to/image.png'; // The minimum likelihood required before returning a match // minLikelihood = LIKELIHOOD_UNSPECIFIED; // The maximum number of findings to report (0 = server maximum) // maxFindings = 0; // The infoTypes of information to match // infoTypes = ['US_MALE_NAME', 'US_FEMALE_NAME']; // Whether to include the matching string // includeQuote = true; Path path = Paths.get(filePath); // detect file mime type, default to application/octet-stream String mimeType = URLConnection.guessContentTypeFromName(filePath); if (mimeType == null) { mimeType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filePath); }//from w w w . ja v a 2s.co m if (mimeType == null) { mimeType = "application/octet-stream"; } byte[] data = Files.readAllBytes(path); ContentItem contentItem = ContentItem.newBuilder().setType(mimeType).setData(ByteString.copyFrom(data)) .build(); InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes) .setMinLikelihood(minLikelihood).setMaxFindings(maxFindings).setIncludeQuote(includeQuote) .build(); InspectContentRequest request = InspectContentRequest.newBuilder().setInspectConfig(inspectConfig) .addItems(contentItem).build(); InspectContentResponse response = dlpServiceClient.inspectContent(request); for (InspectResult result : response.getResultsList()) { if (result.getFindingsCount() > 0) { System.out.println("Findings: "); for (Finding finding : result.getFindingsList()) { if (includeQuote) { System.out.print("Quote: " + finding.getQuote()); } System.out.print("\tInfo type: " + finding.getInfoType().getName()); System.out.println("\tLikelihood: " + finding.getLikelihood()); } } else { System.out.println("No findings."); } } } catch (Exception e) { e.printStackTrace(); System.out.println("Error in inspectFile: " + e.getMessage()); } // [END dlp_inspect_file] }
From source file:org.openeos.attachments.internal.dao.AttachmentServiceImpl.java
private String getMimeType(String file) { String mimeType = URLConnection.guessContentTypeFromName(file); if (mimeType == null) { mimeType = DEFAULT_MIME_TYPE;//from w ww . j a v a2s .c om } return mimeType; }
From source file:com.eharmony.services.swagger.SwaggerResourceServer.java
/** * Serves static resources. Would be better to just punt all this to Jetty, but couldn't figure * out how to make that happen without mucking with Jetty configurations separately for each service. * Doing it here compartmentalizes this from normal service handling flow. *///from w ww. ja v a 2 s . c om @GET @Path("/{fileName:.*}") public Response getStatic(@PathParam("fileName") String file) throws IOException, URISyntaxException { int qp = file.indexOf('?'); file = (qp > 0) ? file.substring(0, qp) : file; file = file.contains("theme") ? file.replaceFirst("theme", themePath) : file; if (!file.contains("..")) { byte[] data = cache.get(file); if (data == null) { Resource[] rz = resolver.getResources(String.format(SWAGGER_UI_PATH, file)); if (rz.length > 0) { try (InputStream result = rz[0].getInputStream()) { data = ByteStreams.toByteArray(result); cache.putIfAbsent(file, data); } } } if (data != null) { String mimeType = URLConnection.guessContentTypeFromName(file); CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(600); return Response.ok(data, mimeType).cacheControl(cacheControl).build(); } } throw new WebApplicationException(Response.Status.NOT_FOUND); }
From source file:eu.openanalytics.shinyproxy.controllers.BaseController.java
protected String resolveImageURI(String resourceURI) { if (resourceURI == null || resourceURI.isEmpty()) return resourceURI; if (imageCache.containsKey(resourceURI)) return imageCache.get(resourceURI); String resolvedValue = resourceURI; if (resourceURI.toLowerCase().startsWith("file://")) { String mimetype = URLConnection.guessContentTypeFromName(resourceURI); if (mimetype == null) { logger.warn("Cannot determine mimetype for resource: " + resourceURI); } else {//from w w w . j a v a2 s . com try (InputStream input = new URL(resourceURI).openConnection().getInputStream()) { byte[] data = StreamUtils.copyToByteArray(input); String encoded = Base64.getEncoder().encodeToString(data); resolvedValue = String.format("data:%s;base64,%s", mimetype, encoded); } catch (IOException e) { logger.warn("Failed to convert file URI to data URI: " + resourceURI, e); } } } imageCache.put(resourceURI, resolvedValue); return resolvedValue; }
From source file:com.evrythng.java.wrapper.service.FileService.java
/** * Obtains a signed url where to upload and uploads there a single {@link java.io.File}. File name for the Cloud will be * determined from {@link java.io.File} provided. Will try to determine content type from {@link java.io.File} provided. * * @param file {@link java.io.File} to upload. * * @return {@link SignedUploadRequest} instance containing url. *//* w w w. j a v a2s . c o m*/ public SignedUploadRequest uploadSingleFile(final java.io.File file) throws EvrythngException, IOException { final String fileName = file.getName(); final String contentType = URLConnection.guessContentTypeFromName(fileName); return uploadSingleFile(new FileToSign(fileName, contentType), file); }
From source file:forseti.MultipartUtility.java
public void addFilePart(String fieldName, FileItem uploadFile) throws IOException { String fileName = uploadFile.getName(); writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"") .append(LINE_FEED);/* www . j a va 2s.c o m*/ writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); writer.flush(); InputStream inputStream = uploadFile.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); }
From source file:HttpClient1.java
/** * Methode to upload a data file./*from w w w . j a va 2 s .com*/ * * @param uploadFile */ public void putData(File uploadFile) { String fileName = uploadFile.getName(); String fieldName = "data"; String boundary = "" + System.currentTimeMillis() + ""; httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); httpConn.setRequestProperty("file", fileName); httpConn.setUseCaches(false); httpConn.setDoOutput(true); httpConn.setDoInput(true); logger.info("PUT Data file on " + url); logger.info("Uploading Data file: " + uploadFile); logger.info("Writing header:" + httpConn.getRequestProperties()); try { httpConn.setRequestMethod("PUT"); } catch (ProtocolException e1) { e1.printStackTrace(); } OutputStream outputStream = null; try { outputStream = (httpConn.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } PrintWriter writer = null; try { writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String LINE_FEED = "\r\n"; logger.debug("Writing body"); writer.append("--" + boundary).append(LINE_FEED); logger.debug("Boundary: " + boundary); writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"") .append(LINE_FEED); logger.debug("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\""); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED); logger.debug("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); logger.debug("Content-Transfer-Encoding: binary"); writer.append(LINE_FEED); writer.flush(); fileToOutputStream(uploadFile, outputStream); try { outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } writer.append(LINE_FEED); writer.flush(); writer.close(); httpConn.disconnect(); try { logger.info( "Server respond: " + httpConn.getResponseCode() + " , " + httpConn.getResponseMessage() + "\n"); } catch (IOException e) { e.printStackTrace(); } }