本文整理汇总了Java中java.net.URLConnection.guessContentTypeFromStream方法的典型用法代码示例。如果您正苦于以下问题:Java URLConnection.guessContentTypeFromStream方法的具体用法?Java URLConnection.guessContentTypeFromStream怎么用?Java URLConnection.guessContentTypeFromStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.URLConnection
的用法示例。
在下文中一共展示了URLConnection.guessContentTypeFromStream方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: contentTest
import java.net.URLConnection; //导入方法依赖的package包/类
@Test
public void contentTest() throws Exception {
URL url = this.getClass().getResource("../../../../amazon-aws-logo.jpg");
String tmpFileName = url.getFile();
File file = new File(tmpFileName);
String fileName = file.getName();
InputStream is = url.openStream();
String contentType = URLConnection.guessContentTypeFromStream(is);
contentHelper.uploadContent(contentType, file.length(), bucketName, fileName, is);
Thread.sleep(500);
boolean doesObjectExist = s3Client.doesObjectExist(bucketName, fileName);
Assert.assertTrue(doesObjectExist);
S3ObjectInputStream inputStream = contentHelper.downloadContent(bucketName, fileName);
Assert.assertNotNull(inputStream);
contentHelper.deleteContent(bucketName, fileName);
Thread.sleep(500);
doesObjectExist = s3Client.doesObjectExist(bucketName, fileName);
Assert.assertFalse(doesObjectExist);
}
示例2: uploadMedia
import java.net.URLConnection; //导入方法依赖的package包/类
private Media uploadMedia(User _user) throws IOException {
URL url = this.getClass().getResource("../../../../amazon-aws-logo.jpg");
String tmpFileName = url.getFile();
File file = new File(tmpFileName);
String fileName = file.getName();
InputStream is = url.openStream();
String contentType = URLConnection.guessContentTypeFromStream(is);
Comment comment = new Comment();
comment.setText("My comment");
Set<Comment> comments = new HashSet<>();
comments.add(comment);
Media tmpMedia = contentFacade.uploadPictureToS3(_user, fileName, is, contentType, comment);
return tmpMedia;
}
示例3: update
import java.net.URLConnection; //导入方法依赖的package包/类
@PUT
@Path(value = "/{id}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void update(@NotNull @PathParam("id") @ApiParam(required = true) String id, @MultipartForm ConnectorFormData connectorFormData) {
if (connectorFormData.getConnector() == null) {
throw new IllegalArgumentException("Missing connector parameter");
}
Connector connectorToUpdate = connectorFormData.getConnector();
if (connectorFormData.getIconInputStream() != null) {
try(BufferedInputStream iconStream = new BufferedInputStream(connectorFormData.getIconInputStream())) {
// URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
// can continue to be used, rather than being consumed.
String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
if (!guessedMediaType.startsWith("image/")) {
throw new IllegalArgumentException("Invalid file contents for an image");
}
MediaType mediaType = MediaType.valueOf(guessedMediaType);
Icon.Builder iconBuilder = new Icon.Builder().mediaType(mediaType.toString());
Icon icon = getDataManager().create(iconBuilder.build());
iconDao.write(icon.getId().get(), iconStream);
connectorToUpdate = connectorToUpdate.builder().icon("db:" + icon.getId().get()).build();
} catch (IOException e) {
throw new IllegalArgumentException("Error while reading multipart request", e);
}
}
getDataManager().update(connectorToUpdate);
}
示例4: imageToEmbed
import java.net.URLConnection; //导入方法依赖的package包/类
private static String imageToEmbed(byte[] image) {
String contentType;
try {
contentType = URLConnection.guessContentTypeFromStream(new BufferedInputStream(new ByteArrayInputStream(image)));
} catch (IOException e) {
contentType = DEFAULT_CONTENT_TYPE;
}
return "data:" + contentType + ";base64," + encodeImage(image);
}
示例5: uploadImages
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Upload an array of images to the server. Currently, the frontend can only handle an image at a time,
* but this method should only require a little modification if we wanted to make possible multiple uploads
* at the same time.
*
* @param files An array of files to upload.
* @return HTTP response of a body containing a JSON object with the generated path,
* using the appropriate status code.
*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<UploadImagesDTO> uploadImages(@RequestParam("files") MultipartFile[] files) {
String path;
UploadImagesDTO uploadFailed = new UploadImagesDTO("", false);
// Generate a random hex string that doesn't already exist
do {
path = getRandomHexString(16);
} while (dao.pathExists(path));
for (MultipartFile file : files) {
String name = file.getOriginalFilename();
try {
InputStream is = new BufferedInputStream(file.getInputStream());
String mimeType = URLConnection.guessContentTypeFromStream(is);
// Return if the image is not the right file type (or if it isn't even an image)
if (!ACCEPTED_FILE_TYPES.contains(mimeType)) {
dao.deleteAllImages(path);
return new ResponseEntity<>(uploadFailed, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
}
if (!dao.saveImage(name, file, path, mimeType)) {
// If saving an image fails for some reason, delete all previously uploaded images and
// return 500
dao.deleteAllImages(path);
return new ResponseEntity<>(uploadFailed, HttpStatus.INTERNAL_SERVER_ERROR);
}
} catch (IOException e) {
e.printStackTrace();
dao.deleteAllImages(path);
return new ResponseEntity<>(uploadFailed, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return new ResponseEntity<>(new UploadImagesDTO(path, true), HttpStatus.OK);
}
示例6: uploadDataToBucket
import java.net.URLConnection; //导入方法依赖的package包/类
private void uploadDataToBucket() throws IOException {
URL url = this.getClass().getResource("../../../../amazon-aws-logo.jpg");
String tmpFileName = url.getFile();
File file = new File(tmpFileName);
String fileName = file.getName();
InputStream is = url.openStream();
String contentType = URLConnection.guessContentTypeFromStream(is);
User userJohn = new User();
userJohn.setEmail("[email protected]");
userJohn.setUserName("jondoe");
userJohn.updatePassword("mypassword");
User _sharedUser = new User();
_sharedUser.setEmail("[email protected]");
_sharedUser.setUserName("aliceN");
_sharedUser.updatePassword("mypwd");
_user = userFacade.register(userJohn);
sharedUser = userFacade.register(_sharedUser);
Comment comment = new Comment();
comment.setText("My comment");
Set<Comment> comments = new HashSet<>();
comments.add(comment);
uploadedMedia = contentFacade.uploadPictureToS3(_user, fileName, is, contentType, comment);
}
示例7: doMultiPart
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Executes MultiPart upload request to an endpoint with provided headers.
*
* @param uri
* endpoint that needs to be hit
* @param file
* file to be uploaded
* @param headers
* Key Value pair of headers
* @return Response Body after executing Multipart
* @throws StockException
* if api doesnt return with success code or when null/empty
* endpoint is passed in uri
*/
public static String doMultiPart(final String uri, final byte[] file,
final Map<String, String> headers) throws StockException {
if (sHttpClient == null) {
sHttpClient = HttpUtils.initialize();
}
HttpResponse response = null;
String responseBody = null;
if (uri == null || uri.isEmpty()) {
throw new StockException(-1, "URI cannot be null or Empty");
}
HttpPost request = new HttpPost(uri);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
request.setHeader(entry.getKey(), entry.getValue());
}
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
if (file != null) {
String contentType = URLConnection.guessContentTypeFromStream(
new ByteArrayInputStream(file));
builder.addBinaryBody("similar_image", file,
ContentType.create(contentType), "file");
}
HttpEntity entity = builder.build();
request.setEntity(entity);
response = sHttpClient.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK
|| response.getStatusLine().getStatusCode()
== HttpStatus.SC_CREATED) {
responseBody = EntityUtils.toString(response.getEntity());
} else if (response.getStatusLine().getStatusCode()
/ HTTP_STATUS_CODE_DIVISOR
== HTTP_STATUS_CODE_API_ERROR) {
responseBody = EntityUtils.toString(response.getEntity());
throw new StockException(response.getStatusLine()
.getStatusCode(), responseBody);
} else if (response.getStatusLine().getStatusCode()
/ HTTP_STATUS_CODE_DIVISOR
== HTTP_STATUS_CODE_SERVER_ERROR) {
throw new StockException(response.getStatusLine()
.getStatusCode(), "API returned with Server Error");
}
} catch (StockException se) {
throw se;
} catch (Exception ex) {
throw new StockException(-1, ex.getMessage());
}
return responseBody;
}
示例8: create
import java.net.URLConnection; //导入方法依赖的package包/类
@POST
@ApiOperation("Updates the connector icon for the specified connector and returns the updated connector")
@ApiResponses(@ApiResponse(code = 200, response = Connector.class, message = "Updated Connector icon"))
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Connector create(MultipartFormDataInput dataInput) {
if (dataInput == null || dataInput.getParts() == null || dataInput.getParts().isEmpty()) {
throw new IllegalArgumentException("Multipart request is empty");
}
if (dataInput.getParts().size() != 1) {
throw new IllegalArgumentException("Wrong number of parts in multipart request");
}
try {
InputPart filePart = dataInput.getParts().iterator().next();
InputStream result = filePart.getBody(InputStream.class, null);
if (result == null) {
throw new IllegalArgumentException("Can't find a valid 'icon' part in the multipart request");
}
try (BufferedInputStream iconStream = new BufferedInputStream(result)) {
MediaType mediaType = filePart.getMediaType();
if (!mediaType.getType().equals("image")) {
// URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
// can continue to be used, rather than being consumed.
String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
if (!guessedMediaType.startsWith("image/")) {
throw new IllegalArgumentException("Invalid file contents for an image");
}
mediaType = MediaType.valueOf(guessedMediaType);
}
Icon.Builder iconBuilder = new Icon.Builder()
.mediaType(mediaType.toString());
Icon icon;
String connectorIcon = connector.getIcon();
if (connectorIcon != null && connectorIcon.startsWith("db:")) {
String connectorIconId = connectorIcon.substring(3);
iconBuilder.id(connectorIconId);
icon = iconBuilder.build();
getDataManager().update(icon);
} else {
icon = getDataManager().create(iconBuilder.build());
}
iconDao.write(icon.getId().get(), iconStream);
Connector updatedConnector = new Connector.Builder().createFrom(connector).icon("db:" + icon.getId().get()).build();
getDataManager().update(updatedConnector);
return updatedConnector;
}
} catch (IOException e) {
throw new IllegalArgumentException("Error while reading multipart request", e);
}
}
示例9: create
import java.net.URLConnection; //导入方法依赖的package包/类
@POST
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation("Creates a new Connector based on the ConnectorTemplate identified by the provided `id` and the data given in `connectorSettings` multipart part, plus optional `icon` file")
@ApiResponses(@ApiResponse(code = 200, response = Connector.class, message = "Newly created Connector"))
public Connector create(@MultipartForm CustomConnectorFormData customConnectorFormData) throws IOException {
final ConnectorSettings connectorSettings = customConnectorFormData.getConnectorSettings();
if (connectorSettings == null) {
throw new IllegalArgumentException("Missing connectorSettings parameter");
}
final ConnectorSettings connectorSettingsToUse;
if (connectorSettings.getConfiguredProperties().containsKey("specification")) {
connectorSettingsToUse = connectorSettings;
} else {
final String specification;
try (BufferedSource source = Okio.buffer(Okio.source(customConnectorFormData.getSpecification()))) {
specification = source.readUtf8();
}
connectorSettingsToUse = new ConnectorSettings.Builder().createFrom(connectorSettings).putConfiguredProperty("specification", specification).build();
}
Connector generatedConnector = withGeneratorAndTemplate(connectorSettingsToUse.getConnectorTemplateId(),
(generator, template) -> generator.generate(template, connectorSettingsToUse));
if (customConnectorFormData.getIconInputStream() != null) {
// URLConnection.guessContentTypeFromStream resets the stream after inspecting the media type so
// can continue to be used, rather than being consumed.
try(BufferedInputStream iconStream = new BufferedInputStream(customConnectorFormData.getIconInputStream())) {
String guessedMediaType = URLConnection.guessContentTypeFromStream(iconStream);
if (!guessedMediaType.startsWith("image/")) {
throw new IllegalArgumentException("Invalid file contents for an image");
}
MediaType mediaType = MediaType.valueOf(guessedMediaType);
Icon.Builder iconBuilder = new Icon.Builder()
.mediaType(mediaType.toString());
Icon icon = getDataManager().create(iconBuilder.build());
iconDao.write(icon.getId().get(), iconStream);
generatedConnector = new Connector.Builder().createFrom(generatedConnector).icon("db:" + icon.getId().get()).build();
} catch (IOException e) {
throw new IllegalArgumentException("Error while reading multipart request", e);
}
}
return getDataManager().create(generatedConnector);
}
示例10: getFilePost
import java.net.URLConnection; //导入方法依赖的package包/类
private HttpPost getFilePost(String str, ArrayList<KVPair<String>> arrayList,
ArrayList<KVPair<String>> arrayList2) throws Throwable {
Iterator it;
HTTPPart stringPart;
String uuid = UUID.randomUUID().toString();
HttpPost httpPost = new HttpPost(str);
httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + uuid);
MultiPart multiPart = new MultiPart();
HTTPPart stringPart2 = new StringPart();
if (arrayList != null) {
it = arrayList.iterator();
while (it.hasNext()) {
KVPair kVPair = (KVPair) it.next();
stringPart2.append("--").append(uuid).append("\r\n");
stringPart2.append("Content-Disposition: form-data; name=\"").append(kVPair.name)
.append("\"\r\n\r\n");
stringPart2.append((String) kVPair.value).append("\r\n");
}
}
multiPart.append(stringPart2);
it = arrayList2.iterator();
while (it.hasNext()) {
kVPair = (KVPair) it.next();
HTTPPart stringPart3 = new StringPart();
File file = new File((String) kVPair.value);
stringPart3.append("--").append(uuid).append("\r\n");
stringPart3.append("Content-Disposition: form-data; name=\"").append(kVPair.name)
.append("\"; filename=\"").append(file.getName()).append("\"\r\n");
String contentTypeFor = URLConnection.getFileNameMap().getContentTypeFor((String)
kVPair.value);
if (contentTypeFor == null || contentTypeFor.length() <= 0) {
if (((String) kVPair.value).toLowerCase().endsWith("jpg") || ((String) kVPair
.value).toLowerCase().endsWith("jpeg")) {
contentTypeFor = "image/jpeg";
} else if (((String) kVPair.value).toLowerCase().endsWith("png")) {
contentTypeFor = "image/png";
} else if (((String) kVPair.value).toLowerCase().endsWith("gif")) {
contentTypeFor = "image/gif";
} else {
InputStream fileInputStream = new FileInputStream((String) kVPair.value);
contentTypeFor = URLConnection.guessContentTypeFromStream(fileInputStream);
fileInputStream.close();
if (contentTypeFor == null || contentTypeFor.length() <= 0) {
contentTypeFor = "application/octet-stream";
}
}
}
stringPart3.append("Content-Type: ").append(contentTypeFor).append("\r\n\r\n");
multiPart.append(stringPart3);
stringPart2 = new FilePart();
stringPart2.setFile((String) kVPair.value);
multiPart.append(stringPart2);
stringPart = new StringPart();
stringPart.append("\r\n");
multiPart.append(stringPart);
}
stringPart = new StringPart();
stringPart.append("--").append(uuid).append("--\r\n");
multiPart.append(stringPart);
httpPost.setEntity(multiPart.getInputStreamEntity());
return httpPost;
}