2010-07-02 71 views
2

我有一個保存表單的jsp頁面,它應該將表單數據發送到遠程servlet,然後將其作爲XML進行計算。它可以工作,但目前我正在創建一個實例和調度程序,它只能與本地servlet一起工作,而我希望它能夠與遠程servlet一起工作。調用遠程Java Servlet

我之前被告知HTTPClient會這樣做,但這件事已經變得如此頭疼,而且對於我想要做的事情來說這似乎是一個完全矯枉過正的事情。必須有一些簡單的方法,而不是用所有這些jar組件和依賴關係來解決問題?

如果可能的話請給示例代碼,我真的一個完整的新手到Java,更是一個PHP的傢伙:P

回答

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); 
    } 
+0

你能告訴我你是如何恢復數據?我需要它 – 2013-01-03 15:24:36