0

我有一个关于将文件(XML 文件)从我的 webapp 服务器发送到另一个使用 Java(struts2 框架)的服务器的简单问题。

希望有人可以看看我的代码,因为我无法检查代码是否可以工作- 另一台服务器(必须接收文件的服务器)仍然没有实现。而且我必须准备我的 webapp 服务器以最正确的方式发送文件。

我有一个 XML 文件路径,以及由 spring 框架填充的服务器地址和端口。

查看互联网上的一些示例以及这个很棒的站点中的一些其他问题,我尝试编写一个简单的代码来将我的文件发送到给定的地址。这是代码:

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();
    }

}

因此,如果有人可以查看我的代码并告诉我您是否认为它不起作用,我将非常感激。如果您认为还有另一种更好的方法可以做到这一点,我也将不胜感激。

谢谢大家,你们总是非常乐于助人;)

问候,

阿莱克斯

4

2 回答 2

3

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.

于 2011-06-20T15:54:24.323 回答
0

我已经查看了如何使用 Apache HttpClient4 和 HttpCore4 库通过 HTTP 来完成它,并且我已经编写了这段代码,你认为它会正常工作吗?非常感谢!

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();
    }
}
于 2011-06-21T00:56:40.427 回答