Aleix
Aleix

Reputation: 743

Java: send a file (XML) from webserver to another server

I have a simple question about sending a file (XML file) from my webapp server to another server with Java (struts2 framework).

I hope someone can give a look to my code, because it is impossible for me to check if the code will work - the other server (the one that have to receive the file) is still not implemented. And I have to prepare my webapp server the most correct possible to send the file.

I have an XML file path, and the server address and the port its filled by the spring framework.

Looking at some examples in internet and also in some other questions in this awesome site, I have tried to write a simple code to send my file to the given address. This is the code:

private String server;
private Integer port;

// getters and settlers methods for server and port properties

public void sendXML(String fileName) throws Exception{
    try{
        Socket socket = new Socket(server, port);

        File file = new File(fileName);

        FileInputStream fis = new FileInputStream(file);

        OutputStream os = socket.getOutputStream();

        byte [] bytearray  = new byte [(int)file.length()];
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(bytearray,0,bytearray.length);
        os.write(bytearray,0,bytearray.length);
        os.flush();
        socket.close();

    }
    catch(IOException e){
        e.printStackTrace();
    }

}

So, I will be very grateful if someone can give a look to my code and tell me if you think that it will not work. If you think that there is another better way to do it I also would be grateful to know it.

Thank you people, you are always really really helpful ;)

Regards,

Aleix

Upvotes: 0

Views: 2491

Answers (2)

Aleix
Aleix

Reputation: 743

I have look how to do it trough HTTP with the Apache HttpClient4 and HttpCore4 libraries and I have wrote this code, you think it would work properly? Thank you very much!

private String server;
//private Integer port;

// getter and settler methods for server property

public void sendXML(String fileName) throws Exception{
    try{
        File file = new File(fileName);
        FileEntity entity = new FileEntity(file, "text/xml; charset=\"UTF-8\"");
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost method = new HttpPost(server);
        method.setEntity(entity);
        HttpResponse response = httpclient.execute(method);
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

Upvotes: 0

artbristol
artbristol

Reputation: 32397

I suggest you use HTTP rather than raw sockets. It will deal with timeouts, chunking, encoding, etc.

Have a look at the commons http library (formerly known as http-client), it will save you writing your own code.

Upvotes: 3

Related Questions