user3688653 user3688653 - 5 months ago 9
Java Question

How to send request and proceed response, and send back to Client?

A Client calls the Servlet via a HTTP Request (via the Browser, post), then the Servlet should send a request (get) to a external Website, and receive the response (post) from the Website.
The Servlets proceed the response and sends a response (post) to the Client.

My question is how to send and receive a request/response inside a Servlet and send something back to the Client?

Answer

You can first create the URL and then use URLConnection object to connect and receive the response as below for GET request/response

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 For POST request/response do this

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);
Comments