在客户端发送google awt servlet中读取数据

时间:2011-07-11 06:43:18

标签: java networking servlets

我想从桌面应用程序向google awt servelet发送一些数据 我正在我的系统(localhost)中尝试这个,因为我已经安装了eclipse插件
我正在发送这样的数据

URL url = new URL("http://localhost:8888/calendar");
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());

String stringTosend = URLEncoder.encode(tf.getText(), "UTF-8");
out.write(stringTosend);

和我的服务器就是这样

public class CalendarServlet extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/plain");
        String input = req.getReader().readLine();
        resp.getWriter().println(input);
    }
}

但我得到的回报是NULL。

1 个答案:

答案 0 :(得分:1)

URLConnection connection = new URL("http://localhost:8888/calendar").openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
OutputStream output = null;
try {
     output = connection.getOutputStream();
     output.write(stringTosend.getBytes(charset));
} finally {
     if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
InputStream response = connection.getInputStream();

<强>参考