Java content type example

Java Email ContentType tutorial with examples

This class represents a MIME Content-Type value. It provides methods to parse a Content-Type string into individual components and to generate a MIME style Content-Type string.

Example

The following code shows how to use ContentType from javax.mail.internet.

import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.ContentType; import javax.mail.internet.MimeBodyPart; public class Pop3 < public static void main(String[] args) < sammleMails();// w w w . d em o 2 s. c o m > static public void sammleMails() < Properties props = new Properties(); String host = "pop.gmx.net"; String username = "analyser2009@gmx.de"; String password = "terminator"; String provider = "pop3"; String smtpHost = "smtp.gmx.net"; props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "false"); try < // Connect to the POP3 server Session session = Session.getDefaultInstance(props, null); session.setDebug(true); Store store = session.getStore(provider); store.connect(host, username, password); // Open the folder Folder inbox = store.getFolder("INBOX"); if (inbox == null) < System.out.println("No INBOX"); System.exit(1); > inbox.open(Folder.READ_ONLY); // Get the messages from the server Message[] message = inbox.getMessages(); for (int i = 0; i < message.length; i++) < Message m = message[i]; System.out.println("-----------------------\nNachricht: " + i); System.out.println("Von: " + Arrays.toString(m.getFrom())); System.out.println("Betreff: " + m.getSubject()); System.out.println("Gesendet am: " + m.getSentDate()); System.out.println("ContentType: " + new ContentType(m.getContentType())); System.out.println("Content: " + m.getContent()); // Nachricht ist eine einfache Text- bzw. HTML-Nachricht if (m.isMimeType("text/plain")) < System.out.println(m.getContent()); > // Nachricht ist eine Multipart-Nachricht (besteht aus mehreren // Teilen) if (m.isMimeType("multipart/*")) < Multipart mp = (Multipart) m.getContent(); for (int j = 0; j < mp.getCount(); j++) < Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) < MimeBodyPart mimePart = (MimeBodyPart) part; if (mimePart.isMimeType("text/plain")) < BufferedReader in = new BufferedReader( new InputStreamReader(mimePart.getInputStream())); for (String line; (line = in.readLine()) != null;) < System.out.println(line); > > > > > // if Multipart > // Close the connection // but don't remove the messages from the server inbox.close(false); store.close(); > catch (Exception ex) < ex.printStackTrace(); >> >
import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Part; import javax.mail.internet.ContentType; import javax.mail.internet.MimeMultipart; import org.apache.commons.codec.binary.Base64; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; public class MultipartMailProcessor < private static String emailAltBodyContent = "Default"; private static byte[] imageinBytes; private static MapString, byte[]> imagesMap = new LinkedHashMapString, byte[]>(); private static Listbyte[]> imageBytesList = new ArrayListbyte[]>(); public static void main(String[] args) throws Exception < Message[] messages = ConnUtil.getMessages(); for (int i = 0; i < messages.length; i++) < ContentType ct = new ContentType(messages[i].getContentType()); System.out.println("Message Content type:" + ct.getPrimaryType() + ":" + ct.getSubType()); // writePlaintextToFile(messages[i]); if (ct.getPrimaryType().equals("multipart")) < handleMultiPart(messages[i]); >// w w w . d e m o2 s . co m > ConnUtil.closeResources(); > public static void handleMultiPart(Message m) throws Exception < MimeMultipart content = (MimeMultipart) m.getContent(); for (int i = 0; i < content.getCount(); i++) < BodyPart part = content.getBodyPart(i); ContentType ct = new ContentType(part.getContentType()); System.out.println("#########Part Number: " + i + " #########"); if (ct.getSubType().equals("alternative")) handleMultiPartAlternative(part); System.out.println("Content-type : " + ct.getPrimaryType() + "/" + ct.getSubType()); System.out.println("Content : " + part.getContent()); System.out.println("Part Filename : " + part.getFileName()); if (part.isMimeType("image/png")) < System.out.println("Image Filename:" + part.getFileName()); ContentFileSaver.writeToFile(part); imageBytesList.add(extractBytes(part)); > > prepareHtml(imageBytesList, emailAltBodyContent); > public static void handleMultiPartAlternative(Part part) throws Exception < ContentType ct = new ContentType(part.getContentType()); System.out.println("Content-type : " + ct.getPrimaryType() + "/" + ct.getSubType()); System.out.println("Content : " + part.getContent()); MimeMultipart mimeMultipart = (MimeMultipart) part.getContent(); System.out.println("Parts Count: " + mimeMultipart.getCount()); System.out.println(mimeMultipart.getBodyPart(0).getContentType()); System.out.println(mimeMultipart.getBodyPart(1).getContentType()); String plainText = (String) mimeMultipart.getBodyPart(0).getContent(); emailAltBodyContent = (String) mimeMultipart.getBodyPart(1).getContent(); > public static void prepareHtml(Listbyte[]> imageBytesList, String altMailContent) throws Exception < Document doc = Jsoup.parse(altMailContent); Elements imgElements = doc.getElementsByTag("img"); System.out.println("Images Size: " + imageBytesList.size()); System.out.println(imgElements.size()); for (int i = 0; i < imgElements.size(); i++) < System.out.println(imgElements.get(i).attr("src")); byte[] s = Base64.encodeBase64(imageBytesList.get(i)); String base64String = new String(s); String srcAttribute = "data:image/png;base64," + base64String; imgElements.get(i).attr("src", srcAttribute); > FileOutputStream fileOutputStream = new FileOutputStream("C:\\temp\\" + "mailMsg.html"); fileOutputStream.write(doc.toString().getBytes()); fileOutputStream.close(); > private static byte[] extractBytes(Part part) throws Exception < InputStream inputStream = (InputStream) part.getContent(); byte[] bArray = new byte[inputStream.available()]; while (((int) inputStream.available()) > 0) < int result = (int) (inputStream.read(bArray)); if (result == -1) break; > return bArray; > >
/******************************************************************************* * Copyright (c) 2006-2010 eBay Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 *******************************************************************************/ import org.ebayopensource.turmeric.runtime.sif.service.Service; import org.ebayopensource.turmeric.runtime.tests.common.sif.BaseCallTest; import org.ebayopensource.turmeric.runtime.tests.common.sif.Test1Driver; import org.ebayopensource.turmeric.runtime.tests.common.sif.Test1Driver.TestMode; import org.ebayopensource.turmeric.runtime.tests.common.util.TestUtils; import org.ebayopensource.turmeric.runtime.tests.service1.sample.types1.MyMessage; import org.junit.Assert; import java.io.ByteArrayOutputStream; import java.net.URL; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.URLDataSource; import javax.mail.internet.ContentType; import javax.mail.util.ByteArrayDataSource; import javax.xml.ws.Dispatch; import javax.xml.ws.Response; /**/* ww w . d e m o 2 s . c o m */ * NOTE: How to test attachments. Currently the mail.jar packaged with ibm JDK * is not compatible with the mail.jar that axis2 is using. So the attachment * testcases are commented out. * * To run the test case in dev box, rename the mail.jar in your * C:\opt\java-ibm. \jre\lib\ext copy the mail.jar from your view's * externalv3\jwsdp\1.2\jwsdp-shared\lib * * Uncomment the DataHandler related code in createBinaryDataHandler() method of * this class and in Test1ServiceImpl. compile them. * * Uncomment the code in AllTests of this package. then run. * * @author wdeng */ public class LocalAttachmentTest extends BaseAttachmentTest < protected static final String ATTACHMENT_SERVICE_NAME = "attachment"; public LocalAttachmentTest() throws Exception < super("attachment"); > /*public LocalAttachmentTest(String configRoot, String entryURL) throws Exception < super(configRoot, entryURL); >*/ protected Test1Driver createDriver() throws Exception < MyMessage msg = TestUtils.createTestMessage(); msg.setBinaryData(getDataHandler()); Test1Driver driver = new Test1Driver(ATTACHMENT_SERVICE_NAME, m_clientName, CONFIG_ROOT, serverUri.toURL(), new String[] < "XML" >, new String[] < "XML" >, "myTestOperation", msg); setupDriver(driver); driver.setExpectingSameMessage(false); return driver; > protected void setupDriver(Test1Driver driver) < driver.setVerifier(new AttachmentVerifier(getDataHandler())); > protected class AttachmentVerifier implements Test1Driver.SuccessVerifier < private byte[] m_data; AttachmentVerifier(DataHandler data) < m_data = getDataFromHandler(data); >public void checkSuccess(Service service, String opName, MyMessage request, MyMessage response, byte[] payloadData) throws Exception < DataHandler handler = response.getBinaryData(); byte[] receivedData = getDataFromHandler(handler); Assert.assertFalse("binary data is null", handler == null); Assert.assertTrue("Attachment data received is not the same", equals(m_data, receivedData)); > @SuppressWarnings("rawtypes") public void checkSuccess(Service service, Dispatch dispatch, Response futureResponse, MyMessage request, MyMessage response, byte[] payloadData, TestMode mode) throws Exception < DataHandler handler = response.getBinaryData(); byte[] receivedData = getDataFromHandler(handler); Assert.assertFalse("binary data is null", handler == null); Assert.assertTrue("Attachment data received is not the same", equals(m_data, receivedData)); > private boolean equals(byte[] s1, byte[] s2) < if (s1 == null) < return s2 == null; > int len = s1.length; if (len != s2.length) < len = s2.length; >for (int i = 0; i < len; i++) < if (s1[i] != s2[i]) < return false; > > return true; > > public static void main(String[] argv) < try < ContentType ct1 = new ContentType( "multipart/related; boundary=MIMEBoundaryurn_uuid_AB4AF6CF4B6DE9EB94118478716760019; type=\"application/xop+xml\"; start=\"\"; start-info=\"text/xml;charset=UTF-8"); System.out.println(ct1.getParameter("start")); System.out.println(ct1.getParameter("start-info")); > catch (Exception e) < e.printStackTrace(); >> >

  • Java Email ContentDisposition setParameter(String name, String value)
  • Java Email ContentDisposition toString()
  • Java javax.mail.internet ContentType
  • Java Email ContentType tutorial with examples
  • Java Email ContentType ContentType(String s)
  • Java Email ContentType setParameterList(ParameterList list)
  • Java Email ContentType toString()

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Java HttpHeaders CONTENT_TYPE

The field CONTENT_TYPE() from HttpHeaders is declared as:

public static final String CONTENT_TYPE = "Content-Type"; 

Example

The following code shows how to use HttpHeaders from javax.ws.rs.core.

Specifically, the code shows you how to use Java HttpHeaders.CONTENT_TYPE.

import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public abstract class BaseController < public static Response buildResponse(Object entity) < return Response.ok(entity).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON + "; charset=utf-8") .build(); > >
import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientResponseContext; import javax.ws.rs.client.ClientResponseFilter; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import java.io.IOException; class FixHeadersClientResponseFilter implements ClientResponseFilter < @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException < responseContext.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); > >
import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * Open Tenure exception object */ public class OTRestException extends WebApplicationException < public OTRestException(int statusCode, String message) < super(Response.status(statusCode).entity(message) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON + "; charset=UTF-8").build()); > >

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Читайте также:  Ioc php для чего
Оцените статью