Java 如何修改 HttpUrlConnection 的标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/480153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:10:57  来源:igfitidea点击:

How to modify the header of a HttpUrlConnection

javahttphttp-headershttpurlconnection

提问by tigger

Im trying to improve the Java Html Document a little but i'm running into problems with the HttpUrlConntion. One thing is that some servers block a request if the user agent is a Java VM. Another problem is that the HttpUrlConnectiondoes not set the Referreror Locationheader field. Since several sites use these fields to verify that the content was accessed from their own site, I'm blocked here as well. As far as I can see the only resolution is to replace the URL handler of the HTTP protocol. Or is there any way to modify the default HTTP Handler?

我试图稍微改进 Java Html 文档,但我遇到了HttpUrlConntion. 一件事是,如果用户代理是 Java VM,则某些服务器会阻止请求。另一个问题是HttpUrlConnection没有设置ReferrerLocation头字段。由于多个站点使用这些字段来验证内容是否是从他们自己的站点访问的,因此我也被阻止在此处。据我所知,唯一的解决方案是替换 HTTP 协议的 URL 处理程序。或者有什么方法可以修改默认的HTTP Handler?

采纳答案by Tom Hawtin - tackline

Open the URLwith URL.openConnection. Optionally cast to HttpURLConnection. Call URLConnection.setRequestProperty/addRequestProperty.

打开URLURL.openConnection。可选择强制转换为HttpURLConnection. 呼叫URLConnection.setRequestProperty/ addRequestProperty

The default User-Agent header value is set from the "http.agent"system property. The PlugIn and WebStart allow you to set this property.

默认的 User-Agent 标头值是从"http.agent"系统属性设置的。PlugIn 和 WebStart 允许您设置此属性。

回答by j pimmel

If you use Apache HttpClientto manage your programmatic HTTP connectivity you get an extremely useful API which makes creating connections (and optional automatic re-connecting on fail), setting Headers, posts vs gets, handy methods for retrieving the returned content and much much more.

如果您使用Apache HttpClient来管理您的编程 HTTP 连接,您将获得一个非常有用的 API,它可以创建连接(以及可选的失败时自动重新连接)、设置标题、帖子与获取、检索返回内容的便捷方法等等.

回答by Nayanava

I solved my problem. We can just send the header to application/json and pass the body as a json object. That simply solves the issue.

我解决了我的问题。我们可以将标头发送到 application/json 并将主体作为 json 对象传递。这只是解决了问题。