Make URL Request from Servlet and retain Header information
-
09-09-2019 - |
Question
I need to make a request from a servlet but I also need to retain all the header information. That is in the request object.
For example, I if I do something like the following from the doGet method, is there a simple way to just pass that information to the URL Connection object?
URL url = new URL();
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setUseCaches(false);
uc.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
dos.writeBytes(strInEnc);
dos.flush();
dos.close();
InputStreamReader in = new InputStreamReader(uc.getInputStream());
int chr = in.read();
while (chr != -1) {
taResults.append(String.valueOf((char) chr));
chr = in.read();
Solution
Use the addRequestProperty
method of URLConnection
.
Enumeration<?> names = req.getHeaderNames();
while (names.hasMoreElements()) {
String key = (String) names.nextElement();
Enumeration<?> values = req.getHeaders(key);
while (values.hasMoreElements()) {
uc.addRequestProperty(key, (String) values.nextElement());
}
}
You'll have a similar set of loops if you use HttpClient, unless it has built-in support for pass-through of a ServletRequest
. (And if it doesn't, why bother with a huge set of additional dependencies, and non-standard API?)
OTHER TIPS
You can enumerate all the headers with the request.getHeaderNames() method. However, I recommend to use HttpClient instead of UrlConnection to make the request.