调用远程Java Servlet

时间:2010-07-02 10:15:35

标签: http jsp servlets

我有一个包含表单的jsp页面,它应该将表单数据发送到远程servlet,然后计算它,然后将其作为XML返回。它工作正常,但目前我正在创建一个只适用于本地servlet的实例和调度程序,而我希望它能够与远程servlet一起使用。

我之前被告知HTTPClient会这样做,但这件事情已经变得如此令人头疼,而且对于我想做的事情来说,这似乎是一种彻底的过度杀伤力。必须有一些简单的方法,而不是使用所有这些jar组件和依赖项?

请尽可能提供示例代码,我真的是Java的新手,更像是一个PHP人:P

1 个答案:

答案 0 :(得分:2)

借助一些在线资源计算出来。必须首先收集提交的值(request.getParamater(“bla”)),构建数据字符串(URLEnconder),启动URLConnection并告诉它打开与指定URL的连接,启动OutputStreamWriter然后告诉它添加数据字符串(URLEncoder),然后最终读取数据并打印出来......

以下是代码的要点:

String postedVariable1 = request.getParameter("postedVariable1");
String postedVariable2 = request.getParameter("postedVariable2");

//Construct data here... build the string like you would with a GET URL     
String data = URLEncoder.encode("postedVariable1", "UTF-8") + "=" + URLEncoder.encode(postedVariable1, "UTF-8");
data += "&" + URLEncoder.encode("postedVariable2", "UTF-8") + "=" + URLEncoder.encode(submitMethod, "UTF-8");

    try {
        URL calculator = new URL("http://remoteserver/Servlet");
        URLConnection calcConnection = calculator.openConnection();
        calcConnection.setDoOutput(true);
        OutputStreamWriter outputLine = new OutputStreamWriter(calcConnection.getOutputStream());
        outputLine.write(data);
        outputLine.flush();


        // Get the response
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(calcConnection.getInputStream()));
        String line;
        //streamReader = holding the data... can put it through a DOM loader?
        while ((line = streamReader.readLine()) != null) {
            PrintWriter writer = response.getWriter();
            writer.print(line);
        }
        outputLine.close();
        streamReader.close();

    } catch (MalformedURLException me) {
        System.out.println("MalformedURLException: " + me);
    } catch (IOException ioe) {
        System.out.println("IOException: " + ioe);
    }