如何从我的java类发送字符串到servlet

时间:2013-12-17 11:42:51

标签: java servlets

Client.java 将字符串发送到servlet

    String url = "http://localhost:8084/Lab/url";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");
            con.setDoInput(true);
            con.setDoOutput(true);
            dos = new DataOutputStream(con.getOutputStream());
            dos.writeBytes(resultJson.toString());
    int responseCode = con.getResponseCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                                con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) 
                System.out.println(inputLine);

            dos.flush();
            dos.close();
            in.close();

的Servlet 从客户端获取值并返回

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

我不知道接下来该做什么。

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

  1. 要将字符串作为参数传递,请将 String url = "[http://localhost:8084/Lab/url]"; 替换为 String url = "[http://localhost:8084/Lab/url?str=YOURSTRING]";
  2. 在servlet中,要检索消息add: String messsage = request.getParameter(“str”);

  3. 在[1]中使用 GET ,我们在包含字符串的URL中传递“str”参数。 我们使用servlet [2]中的getParameter()检索消息。

    正如@Anders所说,我们也可以使用 POST

    来做到这一点

    我希望这有用。

    干杯

    PS:URLS没有[]


    [UPDATE]
    使用POST发送参数

        String param = "str=YOURSTRING";
        String request = "http://localhost:8084/";
        URL url = new URL(request);
        HttpURLConnection connection = (HttpURLConnection)
        url.openConnection();          
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" +  Integer.toString(param.getBytes().length));
        connection.setUseCaches (false);
    
        DataOutputStream out = new DataOutputStream(connection.getOutputStream ());
        out.writeBytes(param);
        out.flush();
        out.close();
        connection.disconnect();