I am trying to copy file through FTPClient and testing in my local system
My code is like this with my IPv4 address as input for host
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUploader {
FTPClient ftp = null;
public FTPUploader(String host, String user, String pwd) throws Exception{
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(user, pwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
public void uploadFile(String localFileFullName, String fileName, String hostDir)
throws Exception {
try(InputStream input = new FileInputStream(new File(localFileFullName))){
this.ftp.storeFile(hostDir + fileName, input);
}
}
public void disconnect(){
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException f) {
// DO NOTHING
}
}
}
public static void main(String[] args) {
try{
System.out.println("Start");
FTPUploader ftpUploader = new FTPUploader("10.66.***.***", "username", "password");
ftpUploader.uploadFile("D:/Venkatesh.pptx", "65.pptx", "C:/Users/VENKATESH/Desktop");
ftpUploader.disconnect();
System.out.println("Done");
}catch(Exception exception){
exception.printStackTrace();
}
}
}
Now by this, Iam getting the following Exception
Start
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:168)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:189)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:278)
at fileTransfer.FTPUploader.<init>(FTPUploader.java:21)
at fileTransfer.FTPUploader.main(FTPUploader.java:51)
What is the mistake iam doing ????
The program is absolutely fine.
Problem is at the server side.
Exception here is :
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
The error is because of wrong credentials ( or ) the server is not started.
The file is transferred after restarting the server :)
Related
I am trying to send an email in my JavaFX application
Everything works perfect, email is sent to Reciepent, i get no exceptions and no errors when i run it in IDE (InteliJ) but when I run the app outside Intelij it doesn't work.
I made simple registration form which saves data from fields into my database:
String username;
String password;
String email;
Random rd = new Random();
int ID;
public void registerUser(javafx.event.ActionEvent ab) {
username = textUser.getText();
password = textPass.getText();
email = textEmail.getText();
ID = rd.nextInt(999999999);
Connection connectt = null;
try {
Class.forName("org.sqlite.JDBC");
connectt = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\barte\\OneDrive\\Desktop\\sqlite databases\\PRODUCTS\\Products.db");
String s = "INSERT INTO Users(Username,Password,Email,UserID) VALUES (?,?,?,?) ";
PreparedStatement registera = connectt.prepareStatement(s);
registera.setString(1, username);
registera.setString(2, password);
registera.setString(3, email);
registera.setInt(4, ID);
System.out.println(username);
System.out.println(password);
System.out.println(email);
registera.executeUpdate();
System.out.println("Added to Database");
sendMail();
registerr.setStyle("-fx-background-color: #69ff59;");
registerr.setText("Check Your MailBox");
registerr.setOnMouseClicked(event -> {
registerr.setText("Email Has been sent");
});
textUser.setText(null);
textEmail.setText(null);
textPass.setText(null);
regiPane.setVisible(false);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
And here is code for sending email:
public void sendMail() throws MessagingException {
String USER_NAME = "stoc****";
String from = USER_NAME;
String PASSWORD = "************";
String pass = PASSWORD;
String RECIPT = textEmail.getText();
String TOPIC = "Welcome " + username + "!";
String BODY = "Dear user! " +
"You can sign into StockFX by your ID/Username and password" +
"User ID: " + ID + "\n" + "Password: " + password + "\n" +
"We would like to thank you for using our services now and in future!";
String[] to = {RECIPT};
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"****", PASSWORD);
}
});
MimeMessage message = new MimeMessage(session);
try {
try {
message.setFrom(new InternetAddress(from));
} catch (MessagingException e) {
e.printStackTrace();
}
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++) {
try {
toAddress[i] = new InternetAddress(to[i]);
} catch (AddressException e) {
e.printStackTrace();
}
}
for (int i = 0; i < toAddress.length; i++) {
try {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
} catch (MessagingException e) {
e.printStackTrace();
}
}
try {
message.setSubject(TOPIC);
} catch (MessagingException e) {
e.printStackTrace();
}
try {
message.setText(BODY);
} catch (MessagingException e) {
e.printStackTrace();
}
try {
message.saveChanges();
} catch (MessagingException e) {
e.printStackTrace();
}
registerr.setStyle("-fx-background-color: #69ff59;");
registerr.setText("You can now log in");
registerr.setDisable(false);
textUser.setText(null);
textEmail.setText(null);
textPass.setText(null);
regiPane.setVisible(false);
Transport transport = session.getTransport("smtp");
System.out.println("get protocl");
transport.connect(host, from, pass);
System.out.println("get host,from and password");
transport.sendMessage(message, message.getAllRecipients());
System.out.println("get recipients");
transport.close();
System.out.println("close");
System.out.println("Email Sent Successfully!");
} finally {
System.out.println("Complete Process");
}
}
Everything works fine inside InteliJ but void sendEmail won't work in runable jar
I am new to Java mail.
Imports:
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.*;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
import java.util.Random;
import java.util.ResourceBundle;
This class is Controller Class
And this is the main Class:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.io.IOException;
public class Main extends Application {
#Override
public void start(Stage UI) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("DashBoard.fxml"));
UI.setTitle("DIREXT SCANNER (DEMO VER 0.5)");
UI.setScene(new Scene(root, 800, 600));
UI.initStyle(StageStyle.UNDECORATED);
UI.setResizable(false);
UI.show();
UI.setFullScreenExitHint("Press 'ESC' to exit full screen");
}
public static void main(String[] args){
launch(args);
}
}
I tried rebuilding project, delete and add libraries again but the same result
Did anybody elese encountered the same problem?
Is it IDE related or am I missing imports or methods?
I tried to look for similar question on forums, I have already fixed few things, as before runable jar wouldn't run at all.
If question exist please can someone provide the link.
edit
this is the error i get when i run jar from PowerShell:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.base/javafx.event.Event.fireEvent(Unknown Source)
at javafx.graphics/javafx.scene.Node.fireEvent(Unknown Source)
at javafx.controls/javafx.scene.control.Button.fire(Unknown Source)
at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(Unknown Source)
at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.base/javafx.event.Event.fireEvent(Unknown Source)
at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.graphics/javafx.scene.Scene$MouseHandler.access$1300(Unknown Source)
at javafx.graphics/javafx.scene.Scene.processMouseEvent(Unknown Source)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at javafx.graphics/com.sun.glass.ui.View.notifyMouse(Unknown Source)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.reflect.Trampoline.invoke(Unknown Source)
at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(Unknown Source)
at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(Unknown Source)
... 52 more
Caused by: java.lang.NoClassDefFoundError: javax/activation/DataHandler
at sample.DashBoardController.registerUser(DashBoardController.java:321)
... 62 more
Caused by: java.lang.ClassNotFoundException: javax.activation.DataHandler
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
... 63 more
I found solution thanks to all your help
What i did, in project structure, I deleted all artifact, modules and libraries and add everything back again then rebuild the project then build the artifact and I also did set my project folder as Source Root and it worked.
If you are using External Libraries So The problem Sometimes Happens in the Path of this Libraries When you extract to jar File , Simple Solution that Sometimes Work is to create new project and create new Files As the Old Project And move them
I have a problem while I try to access big query through Java API from a Java application in my desktop. Code is:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.BigqueryScopes;
import com.google.api.services.bigquery.model.GetQueryResultsResponse;
import com.google.api.services.bigquery.model.QueryRequest;
import com.google.api.services.bigquery.model.QueryResponse;
import com.google.api.services.bigquery.model.TableCell;
import com.google.api.services.bigquery.model.TableRow;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
public class GettingStarted {
public static Bigquery createAuthorizedClient() throws IOException {
HttpTransport transport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
if (credential.createScopedRequired()) {
credential = credential.createScoped(BigqueryScopes.all());
}
return new Bigquery.Builder(transport, jsonFactory, credential)
.setApplicationName("Bigquery Samples")
.build();
}
private static List<TableRow> executeQuery(String querySql, Bigquery bigquery, String projectId)
throws IOException {
QueryResponse query =
bigquery.jobs().query(projectId, new QueryRequest().setQuery(querySql)).execute();
// Execute it
GetQueryResultsResponse queryResult =
bigquery
.jobs()
.getQueryResults(
query.getJobReference().getProjectId(), query.getJobReference().getJobId())
.execute();
return queryResult.getRows();
}
private static void printResults(List<TableRow> rows) {
System.out.print("\nQuery Results:\n------------\n");
for (TableRow row : rows) {
for (TableCell field : row.getF()) {
System.out.printf("%-50s", field.getV());
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
Scanner sc;
if (args.length == 0) {
sc = new Scanner(System.in);
} else {
sc = new Scanner(args[0]);
}
String projectId="glassy-land-140915";
Bigquery bigquery = createAuthorizedClient();
List<TableRow> rows =
executeQuery(
"SELECT corpus as unique_words "
+ "FROM [bigquery-public-data:samples.shakespeare] LIMIT 10",
bigquery,
projectId);
printResults(rows);
}
}
Exception
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:77)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:283)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:868)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at GettingStarted.executeQuery(GettingStarted.java:38)
at GettingStarted.main(GettingStarted.java:73)
You could also use a proxy with you java client
java -Dhttp.proxyHost= -Dhttp.proxyPort= …. -jar you_bg_client.jar
problem was firewall in the network preventing from accessing google cloud. Used a different network and fetched the results.
I am learning RMI and I made a basic program that uses codebase.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server implements sInterface,s2int {
public void go()
{
System.out.println("GO");
}
public void doIt()
{
}
public static void main(String[] args)
{
if(System.getSecurityManager()==null)
{
System.setSecurityManager(new SecurityManager());
}
try
{
System.setProperty("java.rmi.server.hostname","helios");
String s = "SERVER";
Registry r = LocateRegistry.getRegistry();
sInterface stub = (sInterface) UnicastRemoteObject.exportObject(new Server(),0);
r.rebind(s,stub);
}catch(Exception x){x.printStackTrace();}
}
}
Client:
public class Client {
public static void main(String[] args)
{
if(System.getSecurityManager()==null)
{
System.setSecurityManager(new SecurityManager());
}
try{
String name = "SERVER";
Registry r = LocateRegistry.getRegistry(args[0]);
sInterface inf = (sInterface)r.lookup(name);
inf.go();
}catch(Exception x)
{
x.printStackTrace();
}
}
}
Client does not have 's2int' interface and that is downloaded from the codebase.
The commands used to start the server and the client modules are as follows:
java -Djava.rmi.server.codebase=http://helios/~owner/rmi.jar
-Djava.security.policy=server.policy Server
java -Djava.security.policy=client.policy
-Djava.rmi.server.codebase=http://helios/~owner/
-Djava.rmi.server.hostname=helios Client localhost
Now,this works when both the server and client are on the same PC, but when I tried running it on a different PC on the same network, I got a
java.rmi.ConnectException: Connection refused to host: localhost; nested exception is:
java.net.ConnectException: Connection refused: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.createConnection(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.newConnection(Unknown Source)
at sun.rmi.server.UnicastRef.newCall(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at Client.main(Client.java:20)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at
sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(Unknown S
ource) at
sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(Unknown S
ource)
... 6 more
I am not very knowledgeable when it comes to networking. Can anyone explain why it's not working?
Your client is looking up the wrong Registry. It needs to lookup the Registry at the server host, not its own localhost.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
public class SaveImageFromUrl {
public static void main(String[] args) throws Exception {
// proxy settings
System.setProperty("http.proxyHost", "porxyHost");
System.setProperty("http.proxyPort", "8080");
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("userxyz","password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
String imageUrl = "https://graph.facebook.com/10000012233xxxx/picture";
String destinationFile = "D://image4.jpg";
saveImage(imageUrl, destinationFile);
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
My code works fine and downloads image for other imageurl paths.But it is not working when I use String imageUrl = "https://graph.facebook.com/10000012233xxxx/picture";
I am getting the following error :
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at SaveImageFromUrl.saveImage(SaveImageFromUrl.java:33)
at SaveImageFromUrl.main(SaveImageFromUrl.java:28)
You need to make sure that your application can follow redirects, because Facebook is sending one if you request
/{user_id}/picture
To implement this, have a look at http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/
Also, try setting the Proxy authentication like this:
System.setProperty( "http.proxyUserName", "username" );
System.setProperty( "http.proxyPassword", "password" );
I suspect you get the timeout from your proxy connection, but you should be able to test this yourself.
I am trying to get response from below REST api. when I open that URL in browser, I gets xml repsonse from server. but when I am trying to get the same using java program I am getting below exception
IOEXCeption
java.net.UnknownHostException: rxnav.nlm.nih.gov
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at com.test.demo.RestConnector.run(RestConnector.java:22)
at java.lang.Thread.run(Unknown Source)
Pls help me regarding this
below is the code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class RestConnector implements Runnable{
#Override
public void run() {
String URLString = "http://rxnav.nlm.nih.gov/REST/classes?src=MESH";
try {
URL url = new URL(URLString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
if(connection.getResponseCode() != 200){
System.out.println("Failed to connect:"+connection.getResponseCode());
System.out.println("Response Message:"+connection.getResponseMessage());
}
System.out.println("I am here ");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line ;
while((line = reader.readLine()) != null){
System.out.println(line);
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOEXCeption");
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t = new Thread(new RestConnector());
t.start();
}
}
1) The error clearly says "can't resolve hostname".
2) Q: Does your AndroidManifest.xml grant Internet permissions? Make sure it contains this line:
<uses-permission android:name="android.permission.INTERNET" />
3) Q: is this a real device, or an emulator? If the latter, consider recreating your AVD. Believe it or not, that can sometimes help: Android java.net.UnknownHostException: Host is unresolved.
4) Finally, here are some other tips - including proxy server configuration - that might help:
http://eliasbland.wordpress.com/2011/02/22/java-net-unknownhostexception-on-android-a-list-of-possible-causes/