tags:

views:

20

answers:

1

I have a jsp page which holds a form, it is supposed to send off the form data to a remote servlet, which calculates it, and then returns it as XML. It works, but at the moment I'm creating an instance and dispatcher which only works with local servlets whereas I want it to work with a remote servlet.

I was previously told that HTTPClient would do this, but this thing has become such a headache and it seems like a complete overkill for what I want to do. There must be some simple method as opposed to faffing around with all these jar components and dependencies?

Please give sample code if possible, I'm really a complete novice to Java, much more of a PHP guy :P

A: 

Figured it out with the help of some online resources. Had to first collect the submitted values (request.getParamater("bla")), build the data string (URLEnconder), start up a URLConnection and tell it to open a connection with the designated URL, startup an OutputStreamWriter and then tell it to add the string of data (URLEncoder), then finally read the data and print it...

Below is the gist of the code:

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);
    }
Mr Carl