Java Http Server-如何读取从客户端发送的服务器上的xml文件

时间:2016-10-25 08:10:21

标签: java xml http

我已经用Java创建了HTTP服务器,并测试了发送普通字符串并成功收到响应,但我不知道如何读取客户端发布的服务器端文件,我尝试了BuffuredReader和InputStream代码但是浏览器继续加载我的页面并且什么也没显示。

服务器端代码:

public class Server {

public static void main(String[] args) throws Exception {

    HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
    server.createContext("/ahmer", new MyHandler());
    server.setExecutor(null); 
    server.start();

}

static class MyHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange t) throws IOException {


        String response = "Success";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();

    } 
 }

}

客户端代码:

        URL url = new URL("http://localhost:8080/ahmer");
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        String document = "C:\\ahmer.xml";
        FileReader fr = new FileReader(document);
        // specify that we will send output and accept input
        con.setDoInput(true);
        con.setDoOutput(true);
        char[] buffer = new char[1024*10];
        int b_read = 0;
        con.setRequestProperty ( "Content-Type", "text/xml" );
        con.setRequestProperty("SOAPAction","MSMQMessage");
        con.setRequestProperty("Proxy-Accept","NonInteractiveClient" );
        con.setRequestProperty("CONNECTION", "close");
        con.setRequestProperty("CACHE-CONTROL", "no-cache");
        con.setRequestProperty("USER-AGENT", "OpenTV-iAdsResponder_1_0");
        OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
        while ((b_read = fr.read(buffer)) != -1) {
            writer.write(buffer, 0, b_read);
        }
        writer.flush();
        writer.close();
        fr.close();
        int i = con.getResponseCode();
        rs=String.format("Response code: %d",i);
        HttpClient client = new DefaultHttpClient();
        HttpGet requests = new HttpGet("http://localhost:8080/ahmer");
        HttpResponse rss = client.execute(requests);
        String responseAsString = EntityUtils.toString(rss.getEntity());
        con.disconnect();

1 个答案:

答案 0 :(得分:0)

这是我的代码,用于读取从客户端发送到服务器的xml文件。

static class MyHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange t) throws IOException {

        InputStream xml = t.getRequestBody();

        final char[] buffer = new char[1024];
        final StringBuilder out = new StringBuilder();
        try (Reader in = new InputStreamReader(xml, "UTF-8")) {
        for (;;) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
    }
    catch (UnsupportedEncodingException ex) {
        /* ... */
    }
    catch (IOException ex) {
        /* ... */
    } 
}