使用Java Servlet通过HTTP请求发送字符串

时间:2014-01-03 02:53:13

标签: java servlets

您好我正在尝试实现一个接收字符串的服务器,然后生成并向客户端返回另一个字符串,但它运行不正常。

这是我尝试过的: 服务器:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ....
    String str = "something";

    // Return the queueId.
    OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
    writer.write(str);
    writer.flush();
    writer.close();
}

客户端:

    String URL = "http://localhost:8080/"
    String serverURL = URL + "servlet?param=" + someParam;
    final URL url = new URL(serverURL)
    final URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    System.out.println(br.readLine());

但不知何故br.readLine()返回null。在这种情况下哪一方错了?

提前致谢。

1 个答案:

答案 0 :(得分:0)

您的客户应更改如下。由于您使用的是doPOST而不是doGet

String URL = "http://localhost:8080/"
String serverURL = URL + "servlet?param=" + someParam;
final URL url = new URL(serverURL)
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");

final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

System.out.println(br.readLine());

您的代码可能正在调用doGet