Properties props = new Properties();
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");//As discussed but does not work if the leave
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mail#domi.cl","paswwd");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("mail#domi.cl"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("mail#domi.cl"));
message.setSubject("Resumen envio masivo");
message.setText(mensajeMail);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
Below is the StackTrace:
Could not connect to SMTP host: smtp.office365.com, port: 587;
nested exception is:
java.net.ConnectException: Connection refused: connect
javax.faces.el.EvaluationException: java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.office365.com, port: 587;
nested exception is:
java.net.ConnectException: Connection refused: connect
The exception means that you are unable to connect to port 587 on server smtp.office365.com. Verify this using telnet:
telnet smtp.office365.com 587
Possible reasons for this to do not work from your location are:
Misconfigured proxy settings in Java
If it does not work and you are in a company network, then it's most likely the firewall which causes the problem. Also check if password and email is correct.
Maybe also it works with TLS. You should try it.
Please check the SMTP port number for your domain or try my code.
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;
public class Mail {
String senderID;
String senderPassword;
String hostName;
int portNumber;
String attachmentPath;
String subject;
String body;
String cc;
String bcc;
// #=============================================================================================#
public String getBcc() {
return bcc;
}
// #=============================================================================================#
public void setBcc(String bcc) {
this.bcc = bcc;
}
// #=============================================================================================#
public String getCc() {
return cc;
}
// #=============================================================================================#
public void setCc(String cc) {
this.cc = cc;
}
// #=============================================================================================#
public String getBody() {
return body;
}
// #=============================================================================================#
public void setBody(String body) {
this.body = body;
}
// #=============================================================================================#
public String getSubject() {
return subject;
}
// #=============================================================================================#
public void setSubject(String subject) {
this.subject = subject;
}
// #=============================================================================================#
public String getSenderID() {
return senderID;
}
// #=============================================================================================#
public void setSenderID(String senderID) {
this.senderID = senderID;
}
public String getSenderPassword() {
return senderPassword;
}
// #=============================================================================================#
public void setSenderPassword(String senderPassword) {
this.senderPassword = senderPassword;
}
// #=============================================================================================#
public String getHostName() {
return hostName;
}
// #=============================================================================================#
public void setHostName(String hostName) {
this.hostName = hostName;
}
// #=============================================================================================#
public int getPortNumber() {
return portNumber;
}
// #=============================================================================================#
public void setPortNumber(int portNumber) {
this.portNumber = portNumber;
}
// #=============================================================================================#
public String getAttachmentPath() {
return attachmentPath;
}
// #=============================================================================================#
public void setAttachmentPath(String attachmentPath) {
this.attachmentPath = attachmentPath;
}
// #=============================================================================================#
// #=============================================================================================#
public void sendMail(String receiverId) {
try {
// this below commented line for the HTML body text
// MultiPartEmail htmlEmail = new HtmlEmail();
// OR
// HtmlEmail email = new HtmlEmail();
MultiPartEmail email = new MultiPartEmail();
// setting the port number
email.setSmtpPort(getPortNumber());
// authenticating the user
email.setAuthenticator(new DefaultAuthenticator(getSenderID(),
getSenderPassword()));
// email.setDebug(true);
email.setSSL(true);
// setting the host name
email.setHostName(getHostName());
// setting the rciever id
email.addTo(receiverId);
// check for user enterd cc or not
if (getCc() != null) {
// add the cc
email.addCc(getCc());
}
// check for user enterd bcc or not
if (getBcc() != null) {
// add the bcc
email.addBcc(getBcc());
}
// setting the sender id
email.setFrom(getSenderID());
// setting the subject of mail
email.setSubject(getSubject());
// setting message body
email.setMsg(getBody());
// email.setHtmlMsg("<h1>"+getBody()+"</h1>");
// checking for attachment attachment
if (getAttachmentPath() != null) {
// add the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(getAttachmentPath());
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
}
// send the email
email.send();
// System.out.println("Mail sent!");
} catch (Exception e) {
// System.out.println("Exception :: " + e);
// e.printStackTrace();
// gl.writeWarning("Error occured in SendMail.java of sendMailWithAttachment() ");
// gl.writeError(e);
}
}// sendmail()
Related
I flag a message to be deleted after a treatment :
...
import javax.mail.*;
...
public void delete(Message message) throws MessagingException {
try {
message.setFlag(Flags.Flag.DELETED, true);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
...
Then I want to get messages :
...
import com.sun.mail.pop3.POP3Store;
import java.util.Properties;
...
#Value("${mail.host}")
private String host;
#Value("${mail.storeType}")
private String storeType;
#Value("${mail.port}")
private int port;
#Value("${mail.username}")
private String username;
#Value("${mail.password}")
private String password;
#Value("${mail.auth}")
private boolean auth;
#Value("${mail.ssl.trust}")
private String sss_trust;
private POP3Store emailstore = null;
private boolean start = true;
...
public POP3Store getEmailStore() throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.store.protocol", storeType);
properties.setProperty("mail." + storeType + ".host", host);
properties.setProperty("mail." + storeType + ".port", String.valueOf(port));
properties.setProperty("mail." + storeType + ".auth", String.valueOf(auth));
properties.setProperty("mail." + storeType + ".socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail." + storeType + ".ssl.trust", sss_trust);
try {
Session emailSession = Session.getDefaultInstance(properties);
POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
return emailStore;
} catch (NoSuchProviderException e) {
e.printStackTrace();
throw e;
}
}
Folder emailFolder = emailstore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages(); // how to get messages that are not flagged as deleted ?
if (messages != null) {
for (Message message : messages) {
try {
mailService.createTicket(message);
mailService.delete(message);
} catch (Exception ex) {
throw ex;
}
}
}
emailFolder.close(true);
As I commented I want to get messages that are not flagged deleted. How to do that ?
Based on Message class, you can do something like this:
for (Message message : messages) {
if (!message.getFlags().contains(Flags.Flag.DELETED)) { // This will hopefully help
try {
mailService.createTicket(message);
mailService.delete(message);
} catch (Exception ex) {
throw ex;
}
}
}
I am sending an outlook invitation using java mail to four different email servers:
web.de
gmx.net
gmail.com
company's private email server (which is configured on outlook)
The invitation is rendered/previewed on gmail only but we need to render/preview it on every platform.
My main class is
public class Email {
// Constants for the ICalendar methods.
public static final String METHOD_CANCEL = "CANCEL";
public static final String METHOD_PUBLISH = "PUBLISH";
public static final String METHOD_REQUEST = "REQUEST";
// Apply this organizer, if no organizer is given.
private static final String DEFAULT_ORGANIZER = "zain#company.com";
// Common ICalendar fields.
private String method;
private Calendar beginDate;
private Calendar endDate;
private String location;
private int uid;
private String description;
private String subject;
private String organizer;
/*
* #param args
*/
public static void main(String[] args) {
try {
Email email = new Email();
email.send();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
public void send() throws Exception {
try {
String from = "mansoor#company.com";
Properties prop = new Properties();
Address[] receivers = new InternetAddress[] {
new InternetAddress("abc#company.com")
, new InternetAddress("abc#gmail.com")
, new InternetAddress("abc#web.de")
, new InternetAddress("abc#gmx.de")
};
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.host", "smtp.company.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("smtp#company.com", "password");
}
};
Session session = Session.getDefaultInstance(prop, authenticator);
// Define message
MimeMessage message = new MimeMessage(session);
message.addHeaderLine("method=REQUEST");
message.addHeaderLine("charset=UTF-8");
message.addHeaderLine("component=VEVENT");
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, receivers);
message.setSubject("Outlook Meeting Request Using JavaMail");
this.subject = "Meeting Request Test Subject";
this.description = "PLEASE IGNORE THIS MAIL AS IT IS A TEST.";
this.beginDate = new GregorianCalendar(2018, 07-01, 17, 19, 00);
this.endDate = new GregorianCalendar(2018, 07-01, 17, 19, 45);
this.method = Email.METHOD_REQUEST;
this.location = "Office # 13";
// Create the calendar part
BodyPart calendarPart = new MimeBodyPart();
// Fill the message
calendarPart.setHeader("Content-Class", "urn:content- classes:calendarmessage");
calendarPart.setHeader("Content-ID", "calendar_message");
calendarPart.setHeader("Content-Disposition", "inline;filename=Test_invite1.ics");
calendarPart.setFileName("Test_invite1");
calendarPart.setDataHandler(
new DataHandler(
new ByteArrayDataSource(createMessage(), "text/calendar")));// very important
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(calendarPart);
// Put parts in message
message.setContent(multipart);
// send message
Transport.send(message);
for(Address receiver: receivers){
System.out.println(receiver);
}
} catch (MessagingException me) {
System.out.println("Failed sending email");
me.printStackTrace();
} catch (Exception ex) {
System.out.println("Failed sending email");
ex.printStackTrace();
} finally {
System.out.println("End sending email");
System.exit(0);
}
}
public String createMessage() {
// Create the proper date format string required by the ICalendar spec.
final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
final String stringBeginDate = formatter.format(beginDate.getTime());
final String stringEndDate = formatter.format(endDate.getTime());
// Encode the description => mark new lines.
final String encodedDescription = description.replaceAll("\r\n", "\\\\n");
// Use the default organizer if none is given.
if (this.organizer == null) {
this.organizer = DEFAULT_ORGANIZER;
}
// Content string as array.
String[] contents = {
"BEGIN:VCALENDAR",
"METHOD:" + this.method,
"BEGIN:VEVENT",
"UID:" + this.uid,
"DTSTART:" + stringBeginDate,
"DTEND:" + stringEndDate,
"LOCATION:" + this.location,
"DESCRIPTION:" + encodedDescription,
"ATTENDEE;RSVP=TRUE:MAILTO:" + this.organizer,
"ORGANIZER:" + this.organizer,
"SUMMARY:" + this.subject,
"END:VEVENT",
"END:VCALENDAR"
};
// Build a well-formatted string from the array.
StringBuilder sb = new StringBuilder();
for (String line : contents) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append(line);
}
return sb.toString();
}
}
Please add comment if you have any ambiguity before down voting. I have seen so many question on stackoverflow.com but found no proper solution.
Attachments need to be added like this
MailMessage.addAttachment(File file, [String fileName])
, but innerly it seems that fileName is only used for MimeBodyPart.setFileName()
I dont find anyway to use the
MimeBodyPart.setContentID("myID") or MimeBodyPart.setHeader("Content-ID", "myID");
feature, so I can use images embeded in mail with
<img src='CID:MyID'>
It seems MailEngine is in the portal jar so only for internal use, and I was not able to find a solution for MailServiceUtil. Does it mean I need to decode all Liferay high-level API stuff from scratch and use Java Mail API?
I don't think there's a way to do that with Liferay (at least not at version 6.2). But I made it work with standard Java approach. The following is pretty similar to Liferay interface.
public void send(TemplateEmailerMailMessage mailMessage) throws UnsupportedEncodingException {
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailMessage.getFromEmail(), mailMessage.getFromName()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailMessage.getTo()));
message.setSubject(mailMessage.getSubject());
if (mailMessage.isHtmlFormat()) {
message.setText(mailMessage.getBody(), "text/html");
} else {
message.setText(mailMessage.getBody());
}
// create container for attachments and body parts
Multipart multipart = new MimeMultipart();
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailMessage.getBody(), "text/html; charset=UTF-8");
multipart.addBodyPart(messageBodyPart);
// add attachments one by one
for (File file : mailMessage.getFileAttachments()) {
BodyPart messageAttachmentPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageAttachmentPart.setDataHandler(new DataHandler(source));
messageAttachmentPart.setFileName(file.getName());
// set Content-ID so it is recognized by <img src="cid: ... ">
messageAttachmentPart.setHeader("Content-ID", "<" + file.getName() + ">");
multipart.addBodyPart(messageAttachmentPart);
}
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
The message object
public class TemplateEmailerMailMessage {
private String fromEmail;
private String fromName;
private String to;
private String body;
private String subject;
private boolean htmlFormat;
private List<File> fileAttachments = new ArrayList<>();
public void addAttachment(File file) {
fileAttachments.add(file);
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public boolean isHtmlFormat() {
return htmlFormat;
}
public void setHtmlFormat(boolean htmlFormat) {
this.htmlFormat = htmlFormat;
}
public List<File> getFileAttachments() {
return fileAttachments;
}
public void setFileAttachments(List<File> fileAttachments) {
this.fileAttachments = fileAttachments;
}
public String getFromEmail() {
return fromEmail;
}
public void setFromEmail(String fromEmail) {
this.fromEmail = fromEmail;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public void setFrom(String fromEmail, String fromName) {
this.fromEmail = fromEmail;
this.fromName = fromName;
}
}
I want to send a mail to a mailing list every period of time (like every 40min or hour) with java on a unix server.
I'd like any code or tutorial to be able to do this.
Thanks
Sending a mail to a mailing list does not differ from sending a regular mail. The simplest way is to use commons-email. Check its examples.
JavaMail is the usual approach for this. You will need a SMTP-server for JavaMail to connect to.
String[] mailToId = {
"abc#mail.com",
"abc22#mail.com",
"abc33#mail.com"
};
for (int i = 0; i < mailToId.length; i++) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToId[i]));;
}
In your java class you can use array of mail address and one by one mail address can call using for loop.
Within the for loop you can call
message.addRecipient();
method with array name.
look at the above example:
If it is not necessary to USE SMTP - java mail enough
Simple example
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender {
private static String host = "";
private static String user = "";
private static String password = "";
private static int port = 465;
private static String from = "";
private static String to = "";
private static String auth = "true";
private static String debug = "false";
private static String socket_factory = "javax.net.ssl.SSLSocketFactory";
private static String subject = "";
private static String text = "";
/**
* Constructor. Fields - parameters for send mail.
*
* #param host - mail server.
* #param user - user
* #param password - login
* #param port - port
* #param from - mail from address
* #param to - mail to address
* #param subject - subject
* #param text - text of mail
*/
public MailSender(String host, String user, String password, int port,
String from, String to, String subject, String text) {
if (!host.isEmpty())
setHost(host);
if (!user.isEmpty())
setUser(user);
if (!password.isEmpty())
setPassword(password);
if (port == 0)
setPort(port);
if (!from.isEmpty())
setFrom(from);
if (!to.isEmpty())
setTo(to);
if (!subject.isEmpty())
setSubject(subject);
if (!text.isEmpty())
setText(text);
}
/**
* Send mail with parameters from constructor.
*/
public void send() {
// Use Properties object to set environment properties
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", getHost());
props.put("mail.smtp.port", getPort());
props.put("mail.smtp.user", getUser());
props.put("mail.smtp.auth", getAuth());
props.put("mail.smtp.starttls.enable","true");//for gmail?
props.put("mail.smtp.debug", getDebug());
props.put("mail.smtp.socketFactory.port", getPort());
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");//for gmail?
props.put("mail.smtp.socketFactory.fallback", "false");
try {
// Obtain the default mail session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(new Boolean(getDebug()));
// Construct the mail message
MimeMessage message = new MimeMessage(session);
message.setText(getText());
message.setSubject(getSubject());
message.setFrom(new InternetAddress(getFrom()));
message
.addRecipient(RecipientType.TO,
new InternetAddress(getTo()));
message.saveChanges();
// Use Transport to deliver the message
Transport transport = session.getTransport("smtp");
transport.connect(getHost(), getUser(), getPassword());
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getHost() {
return host;
}
public static void setHost(String host) {
MailSender.host = host;
}
public static String getUser() {
return user;
}
public static void setUser(String user) {
MailSender.user = user;
}
public static String getPassword() {
return password;
}
public static void setPassword(String password) {
MailSender.password = password;
}
public static int getPort() {
return port;
}
public static void setPort(int port) {
MailSender.port = port;
}
public static String getFrom() {
return from;
}
public static void setFrom(String from) {
MailSender.from = from;
}
public static String getTo() {
return to;
}
public static void setTo(String to) {
MailSender.to = to;
}
public static String getAuth() {
return auth;
}
public static void setAuth(String auth) {
MailSender.auth = auth;
}
public static String getDebug() {
return debug;
}
public static void setDebug(String debug) {
MailSender.debug = debug;
}
public static String getSocket_factory() {
return socket_factory;
}
public static void setSocket_factory(String socketFactory) {
socket_factory = socketFactory;
}
public static String getSubject() {
return subject;
}
public static void setSubject(String subject) {
MailSender.subject = subject;
}
public static String getText() {
return text;
}
public static void setText(String text) {
MailSender.text = text;
}
I am developing a Java webservice application (with JAX-WS) that has to use two different proxies to establish separated connections to internet and an intranet. As solution I tried to write my own java.net.ProxySelector that returns a java.net.Proxy instance (of type HTTP) for internet or intranet.
In a little test application I try to download webpage via URL.openConnection(), and before I replaced the default ProxySelector with my own. But it results in an exception:
java.net.SocketException: Unknown proxy type : HTTP
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:370)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:844)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:792)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:703)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1026)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
at norman.test.ProxyTest.conntectToRmViaProxy(ProxyTest.java:42)
at norman.test.ProxyTest.main(ProxyTest.java:65)
Question: "Why tries the application to establish a connection via SOCKS, if my ProxySelector only returns a HTTP Proxy?"
2 Question: "Is there a alternative, to define different proxies for each connection?"
This is my ProxySelector:
public class OwnProxySelector extends ProxySelector {
private Proxy intranetProxy;
private Proxy extranetProxy;
private Proxy directConnection = Proxy.NO_PROXY;
private URI intranetAddress;
private URI extranetAddress;
/* (non-Javadoc)
* #see java.net.ProxySelector#connectFailed(java.net.URI, java.net.SocketAddress, java.io.IOException)
*/
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
// Nothing to do
}
/* (non-Javadoc)
* #see java.net.ProxySelector#select(java.net.URI)
*/
public List select(URI uri) {
ArrayList<Proxy> result = new ArrayList<Proxy>();
if(intranetAddress.getHost().equals(uri.getHost()) && intranetAddress.getPort()==uri.getPort()){
result.add(intranetProxy);
System.out.println("Adding intranet Proxy!");
}
else if(extranetAddress.getHost().equals(uri.getHost()) && extranetAddress.getPort()==uri.getPort()){
result.add(extranetProxy);
System.out.println("Adding extranet Proxy!");
}
else{
result.add(directConnection);
System.out.println("Adding direct connection!");
}
return result;
}
public void setIntranetProxy(String proxyAddress, int proxyPort){
if(proxyAddress==null || proxyAddress.isEmpty()){
intranetProxy = Proxy.NO_PROXY;
}
else{
SocketAddress address = new InetSocketAddress(proxyAddress, proxyPort);
intranetProxy = new Proxy(Proxy.Type.HTTP, address);
}
}
public void setExtranetProxy(String proxyAddress, int proxyPort){
if(proxyAddress==null || proxyAddress.isEmpty()){
extranetProxy = Proxy.NO_PROXY;
}
else{
SocketAddress address = new InetSocketAddress(proxyAddress, proxyPort);
extranetProxy = new Proxy(Proxy.Type.HTTP, address);
}
}
public void clearIntranetProxy(){
intranetProxy = Proxy.NO_PROXY;
}
public void clearExtranetProxy(){
extranetProxy = Proxy.NO_PROXY;
}
public void setIntranetAddress(String address) throws URISyntaxException{
intranetAddress = new URI(address);
}
public void setExtranetAddress(String address) throws URISyntaxException{
extranetAddress = new URI(address);
}
}
This is the test class:
public class ProxyTest {
OwnProxySelector ownSelector = new OwnProxySelector();
public ProxyTest(){
ownSelector.setIntranetProxy("intranet.proxy", 8123);
try {
ownSelector.setIntranetAddress("http://intranet:80");
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ownSelector.setExtranetProxy("", 0);
try {
ownSelector.setExtranetAddress("http://www.example.com:80");
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ProxySelector.setDefault(ownSelector);
}
public void conntectToRmViaProxy(boolean internal, String connectAddress){
try {
URL url = new URL(connectAddress);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println(conn.getResponseMessage());
}
else{
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int tmp = reader.read();
while(tmp != -1){
System.out.print((char)tmp);
tmp = reader.read();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
ProxyTest proxyText = new ProxyTest();
proxyText.conntectToRmViaProxy(true, "http://intranet:80");
}
}
Ok, I have found the problem.
The HttpURLConnection did the OwnProxySelector.select() twice if the requested URL does not contain a port.
At first, HttpURLConnection invoked the select() with an URI, with the Scheme of "http" but no port. The select() checks whether the host address and port are euqal to intranetAddress or extranetAddress. This didn't match, because the port was not given. So the select return a Proxy for a direct connection.
At the second HttpURLConnection invoked the select() with an URI, with the Scheme of "socket" and port 80. So, because the select() checks host address and port, but not the scheme, it returned a HTTP proxy.
Now here is my corrected version of OwnProxySelector. It checks the scheme and sets the default port for HTTP or HTTPS if the port is not given by the URI. Also it asks the Java standard ProxySelector, if no HTTP or HTTPS scheme is given.
public class OwnProxySelector extends ProxySelector {
private ProxySelector defaultProxySelector;
private Proxy intranetProxy;
private Proxy extranetProxy;
private Proxy directConnection = Proxy.NO_PROXY;
private URI intranetAddress;
private URI extranetAddress;
public OwnProxySelector(ProxySelector defaultProxySelector){
this.defaultProxySelector = defaultProxySelector;
}
/* (non-Javadoc)
* #see java.net.ProxySelector#connectFailed(java.net.URI, java.net.SocketAddress, java.io.IOException)
*/
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
// Nothing to do
}
/* (non-Javadoc)
* #see java.net.ProxySelector#select(java.net.URI)
*/
public List select(URI uri) {
ArrayList<Proxy> result = new ArrayList<Proxy>();
if(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")){
int uriPort = uri.getPort();
// set default http and https ports if port is not given in URI
if(uriPort<1){
if(uri.getScheme().equalsIgnoreCase("http")){
uriPort = 80;
}
else if(uri.getScheme().equalsIgnoreCase("https")){
uriPort = 443;
}
}
if(intranetAddress.getHost().equals(uri.getHost()) && intranetAddress.getPort()==uriPort){
result.add(intranetProxy);
System.out.println("Adding intranet Proxy!");
}
else if(extranetAddress.getHost().equals(uri.getHost()) && extranetAddress.getPort()==uriPort){
result.add(extranetProxy);
System.out.println("Adding extranet Proxy!");
}
}
if(result.isEmpty()){
List<Proxy> defaultResult = defaultProxySelector.select(uri);
if(defaultResult!=null && !defaultResult.isEmpty()){
result.addAll(defaultResult);
System.out.println("Adding Proxis from default selector.");
}
else{
result.add(directConnection);
System.out.println("Adding direct connection, because requested URI does not match any Proxy");
}
}
return result;
}
public void setIntranetProxy(String proxyAddress, int proxyPort){
if(proxyAddress==null || proxyAddress.isEmpty()){
intranetProxy = Proxy.NO_PROXY;
}
else{
SocketAddress address = new InetSocketAddress(proxyAddress, proxyPort);
intranetProxy = new Proxy(Proxy.Type.HTTP, address);
}
}
public void setExtranetProxy(String proxyAddress, int proxyPort){
if(proxyAddress==null || proxyAddress.isEmpty()){
extranetProxy = Proxy.NO_PROXY;
}
else{
SocketAddress address = new InetSocketAddress(proxyAddress, proxyPort);
extranetProxy = new Proxy(Proxy.Type.HTTP, address);
}
}
public void clearIntranetProxy(){
intranetProxy = Proxy.NO_PROXY;
}
public void clearExtranetProxy(){
extranetProxy = Proxy.NO_PROXY;
}
public void setIntranetAddress(String address) throws URISyntaxException{
intranetAddress = new URI(address);
}
public void setExtranetAddress(String address) throws URISyntaxException{
extranetAddress = new URI(address);
}
}
But it is curious to me, that the HttpURLConnection did a second invoke of select(), when it got a direct connection Proxy from the first invoke.