客戶端通過HTTP請求(通過瀏覽器發送)調用Servlet,然後Servlet應該向外部網站發送請求(get),並從網站接收響應(post)。 Servlets繼續響應並向客戶端發送響應(post)。如何發送請求並繼續回覆,併發送回客戶?
我的問題是如何發送和接收Servlet中的請求/響應並將某些內容發送回客戶端?
客戶端通過HTTP請求(通過瀏覽器發送)調用Servlet,然後Servlet應該向外部網站發送請求(get),並從網站接收響應(post)。 Servlets繼續響應並向客戶端發送響應(post)。如何發送請求並繼續回覆,併發送回客戶?
我的問題是如何發送和接收Servlet中的請求/響應並將某些內容發送回客戶端?
您可以先創建URL,然後使用URLConnection對象連接和接收響應,下面的GET請求/響應
URL url = new URL(urlString);
HttpURLConnection c = (HttpURLConnection)url.openConnection(); //connecting to url
c.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); //stream to resource
String str;
while ((str = in.readLine()) != null) //reading data
responsestring += str+"\n";//process the response and save it in some string or so
in.close(); //closing stream
response.getWriter().write(responsestring);
UPDATE 對於POST請求/響應這樣做
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
String urlParameters = ..;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer res = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
res.append(inputLine);
}
in.close();
//process response
response.getWriter().write(res);
thx,這工作完美! – user3688653
您可以使用以下格式的請求的集合屬性:request.setAttribute(String key, Object value)
。
例子:
public class FindPerson extends HttpServlet {
// ... doGet implementation
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// data to send to the client
String name = "John White";
int age = 54;
// Adding attributes to the request
request.setAttribute("personName", name);
request.setAttribute("personAge", age);
// Sending the result to the.jsp page
getServletContext().getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);
}
}
}
在此之後,您可以使用JSTL閱讀JSP頁面上這樣的數據:
<p>Name: ${ requestScope.personName } </p>
<p>Age: ${ requestScope.personAge } </p>
其中personName
和personAge
是鍵地圖。你使用request.setAttribute
來設置它們。
!!!更新!
在你的情況下,你會調用其他的servlet,它將執行對外部站點的請求等。所有這些(從外部站點收集數據+處理這些數據)將被放置代替設置的代碼姓名和年齡的值(見上面的例子)。 希望它有幫助!
URL url = new URL(urlString);
HttpURLConnection c = (HttpURLConnection)url.openConnection(); //connecting to url
c.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); //stream to resource
String str;
while ((str = in.readLine()) != null) //reading data
responsestring += str+"\n";//process the response and save it in some string or so
in.close(); //closing stream
response.getWriter().write(responsestring);
您的意思是Webservices? –
與外部webside我的意思是一個像eBay一樣的正常web服務,它在html f.E中給出了一個post響應。 – user3688653