从 Servlet 发出 URL 请求并保留 Header 信息
我需要从 servlet 发出请求,但我还需要保留所有标头信息。 那是在请求对象中。
例如,如果我从 doGet 方法执行类似以下操作,是否有一种简单的方法将该信息传递给 URL Connection 对象?
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();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
URLConnection
的addRequestProperty
方法。如果您使用 HttpClient,您将拥有一组类似的循环,除非它具有对
ServletRequest
传递的内置支持。 (如果没有,为什么还要费心去处理一大堆额外的依赖项和非标准 API?)Use the
addRequestProperty
method ofURLConnection
.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?)您可以使用 request.getHeaderNames() 方法枚举所有标头。 但是,我建议使用 HttpClient 而不是 UrlConnection 来发出请求。
You can enumerate all the headers with the request.getHeaderNames() method. However, I recommend to use HttpClient instead of UrlConnection to make the request.