Java:发送前显示 HttpURLConnection 的请求
我想使用 HttpURLConnection
对服务器进行一些 API 调用。但请求不成功,返回:
<error>
<http_status>400 Bad Request</http_status>
<message>Unexpected request Content-Type header ''. Expecting 'application/x-www-form-urlencoded'.</message>
</error>
所以我想检查发送到服务器的“真实”内容是什么。我所说的真实内容是指确切的 HTTP 请求。
我有什么想法可以看到这个吗?
编辑: 根据这里的第一个答案,我应该澄清我的问题:我想避免使用像 HTTP 嗅探器或任何东西这样的外部程序,我希望有一个函数或属性或任何包含我正在寻找的信息的东西。
如果情况并非如此,是否有人知道是否可以手动重建此信息(例如通过调用 getRequestMethod() 等多个函数)
我经常遇到这个问题,因此值得自己努力构建此类功能。只需知道如何:)
I want to make some API calls to a server using HttpURLConnection
. But the requests are not successful, returning:
<error>
<http_status>400 Bad Request</http_status>
<message>Unexpected request Content-Type header ''. Expecting 'application/x-www-form-urlencoded'.</message>
</error>
So I want to check what the "real" content is that is being sent to the server. By real content I mean the exact HTTP request.
Any ideas how I can see this?
Edit:
Based on the first answers here I should clarify my problem: I want to avoid using an external program like HTTP sniffer or anything and I was hoping that there is a function or a property or whatever that holds the information I am looking for.
If that is not the case, does someone know if this information can be manually rebuilt (for example by calling several functions like getRequestMethod(), etc.)
I am facing this problem kinda often so that it's worth the effort to build such functionality myself. Just need to know how :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以通过启用 java.logging 将 HttpURLConnection 置于调试模式,
并将以下属性放入logging.properties(默认在 JRE_HOME\lib 中)
You can put the HttpURLConnection in debug mode by enabling java.logging with
and put in logging.properties (by default in JRE_HOME\lib) the following property
tcpdump 可以工作,但是很难让它做你想要的事情。 NetCat 更加用户友好(这是项目页面:http://netcat.sourceforge.net/ - 大多数Unix 平台已经包含它)。
这将侦听 TCP 端口 9999,当 HTTP 客户端连接时,它将打印出请求的全文。
tcpdump will work, but it can be hard to make it do what you want. NetCat is more user-friendly (here's the project page: http://netcat.sourceforge.net/ - most Unix platforms already include it).
This will listen on TCP port 9999, and when an HTTP client connects, it'll print out the full text of the request.
接受的解决方案对我不起作用。但所做的是
The accepted solution did not work for me. But what did was
使用 tcpdump 之类的工具,它可以转储计算机发出或接收的实际网络数据包。
Use something like tcpdump, which can dump the actual network packets that are emitted or received by your computer.
在 JDK 11 上,我能够记录所有 http 连接,将
java.util.logging.ConsoleHandler.level
设置为FINEST
并在文件中添加以下行logging.properties
默认情况下位于 %JAVA_HOME%/conf 中:On JDK 11 I was able to log all the http connections, setting
java.util.logging.ConsoleHandler.level
toFINEST
and adding the following lines in the filelogging.properties
which is by default in %JAVA_HOME%/conf: