2010-04-01 113 views
1
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    URL url = new URL("http://localhost:8080/testy/Out"); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.setDoOutput(true); 
    connection.setRequestMethod("POST");  
    PrintWriter out = response.getWriter(); 
    for(Enumeration e = request.getHeaderNames(); e.hasMoreElements();) { 
     Object o = e.nextElement(); 
     String value = request.getHeader(o.toString()); 
     out.println(o + "--is--" + value + "<br>"); 
     connection.setRequestProperty((String) o, value); 
    } 
    connection.connect(); 
} 

我寫上面的代碼在servlet張貼形式所以比這個servlet一些替換的位置,但它不是working.is它好使用connection.setRequestProperty設置頭文件字段與傳入servlet請求中的內容。從請求對象的請求報頭複製到URLConnection對象

回答

1

我認爲你正在尋找

RequestDispatcher rd; 
rd = getServletContext().getRequestDispatcher("pathToServlet"); 
rd.forward(request, response); 
+0

沒有實際上我試圖獲取一些遠程URL與當前請求的標題。 – 2010-04-01 12:09:44

+0

或事後其實不是..?否則將它設置爲接受似乎是錯誤的。 – BalusC 2010-04-01 22:50:28

1

URLConnection懶洋洋地被執行。也就是說,它不會實際上觸發HTTP請求,直到您獲取有關HTTP響應的一些信息。例如。

int responseCode = httpUrlConnection.getResponseCode(); 

InputStream responseBody = urlConnection.getInputStream(); 

String statusHeader = urlConnection.getHeaderField(null); 

connection.connect();是由完全是多餘的方式。它已在您撥打url.openConnection();時執行。此外connection.setRequestMethod("POST");是完全superflous,connection.setDoOutput(true)已經這樣做。也就是說,如果目標實際上位於同一機器上託管的同一個webapp上下文中,那麼有更多的方法可以調用它,而不是創建到它的HTTP連接,例如轉發或重定向請求。

+0

是的,它添加一行後connectin.getHeaderField(); – 2010-04-01 12:12:13

+0

「connection.connect();是完全多餘的方式」 我想connection.openConnection()讓一個Manipulate參數影響到遠程資源的連接。 \t while connection.connect()用於與資源進行交互;查詢連接後的標題字段和內容。 http://java.sun.com/javase/6/docs/api/java/net/URLConnection.html – 2010-04-01 12:18:50

+0

的確如此,但在HTTP連接的情況下它仍然是超級的。離開它,你會看到它只是工作。 – BalusC 2010-04-01 22:51:42