Я настроил Java приложение, используя OAUTH2, но оно выдает ошибку. Может кто-нибудь предложить мне решение? '
Ниже приведен код:
public static void main (String args[]){
String TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token";
String oauthClientId = "558561226799-6nvqdl1kabh863g1a1184t3t7fcvu82e.apps.googleusercontent.com";
String oauthSecret = "UAPodrF7mIAverk_-A8wlWyL";
String refreshToken = "1//0gyh0jPCTq5GSCgYIARAAGBASNwF-L9IrGNizcIn4l4tGhlORji0X6zqFsV4rsB-niM1lNtJa9nVedsTWWPBt9Uuj8pOPcHNrpfc";
String accessToken = "ya29.a0Ae4lvC2p0j2MK6Wv5CcXvcB9VwJmukivtY7M6y6ZBntBdIls5XAXe4TCjt9zr5VuWolB0CdRJjL6UBIz5mqj63KvNxjAYU0DeNsZGbWrz7daP624ruvM-DYsvHSUx1jrUcudiUDF2YhQc3lHH8WXrAhanWIBakI170w";
long tokenExpires = 1458168133864L;
String username="bittu9601164625@gmail.com";
if (System.currentTimeMillis() > tokenExpires) {
try {
String request = "client_id=" + URLEncoder.encode(oauthClientId, "UTF-8")
+ "&client_secret=" + URLEncoder.encode(oauthSecret, "UTF-8")
+ "&refresh_token=" + URLEncoder.encode(refreshToken, "UTF-8")
+ "&grant_type=refresh_token";
HttpURLConnection conn = (HttpURLConnection) new URL(TOKEN_URL).openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(request); // note: println causes error
out.flush();
out.close();
conn.connect();
try {
HashMap<String, Object> result;
result = new ObjectMapper().readValue(conn.getInputStream(), new TypeReference<HashMap<String, Object>>() {
});
accessToken = (String) result.get("access_token");
tokenExpires = System.currentTimeMillis() + (((Number) result.get("expires_in")).intValue() * 1000);
} catch (IOException e) {
String line;
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
while ((line = in.readLine()) != null) {
System.out.println(line);
}
System.out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
String mailUsername = "bittu9601164625@gmail.com";
Properties props = new Properties();
props.put("mail.smtp.ssl.enable", "true"); // required for Gmail
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
try {
Session session = Session.getInstance(props);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(mailUsername));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailUsername));
msg.setSubject("JavaMail OAuth2 test");
msg.setSentDate(new Date());
msg.setText("Hello, world with OAuth2!\n");
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", username, accessToken);
transport.send(msg, msg.getAllRecipients());
} catch (AddressException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
Ниже приведена ошибка, которую я получаю, я не упомянул хост как localhost или номер порта , метод подключения не работает? :
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused (Connection refused)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:120)
at com.rapidbox.wmscore.service.impl.VendorServiceImpl.main(VendorServiceImpl.java:158)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:607)
at java.net.Socket.connect(Socket.java:556)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
... 7 more
Process finished with exit code 0
Пожалуйста, кто-нибудь, скажите мне, что я делаю неправильно. Также, если есть альтернативное решение муравья, то это будет оценено.