如何发送请求并继续回复,并发送回客户端?

时间:2014-07-22 09:05:29

标签: java servlets request response

客户端通过HTTP请求(通过浏览器,帖子)调用Servlet,然后Servlet应该向外部网站发送请求(get),并从网站接收响应(post)。 Servlet继续响应并向客户发送响应(发布)。

我的问题是如何在Servlet中发送和接收请求/响应并将内容发送回客户端?

3 个答案:

答案 0 :(得分:1)

您可以先创建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);

<强>更新 对于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);

答案 1 :(得分:0)

您可以使用此表单中的请求的属性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>

其中personNamepersonAge是地图的。您可以使用request.setAttribute设置它们。

!!!修订!!!

在您的情况下,您将调用其他servlet,它们将对外部站点执行请求等。所有这些(从外部站点收集数据+处理此数据)将被放入而不是设置值的代码名称和年龄(见上例)。 希望它有所帮助!

答案 2 :(得分:0)

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);
相关问题