24

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 :)

Michael Currie
  • 13,721
  • 9
  • 42
  • 58
Hirnhamster
  • 7,101
  • 8
  • 43
  • 73
  • Possible duplicate of [How to enable wire logging for a java HttpURLConnection traffic?](http://stackoverflow.com/questions/1445919/how-to-enable-wire-logging-for-a-java-httpurlconnection-traffic) – Vadzim Oct 09 '15 at 10:22

5 Answers5

14

You can put the HttpURLConnection in debug mode by enabling java.logging with

-Djava.util.logging.config.file=logging.properties

and put in logging.properties (by default in JRE_HOME\lib) the following property

sun.net.www.protocol.http.HttpURLConnection.level = ALL
RealHowTo
  • 34,977
  • 11
  • 70
  • 85
5

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).

nc -l 9999

This will listen on TCP port 9999, and when an HTTP client connects, it'll print out the full text of the request.

Mike Baranczak
  • 8,291
  • 8
  • 47
  • 71
3

The accepted solution did not work for me. But what did was

static {
    ConsoleHandler handler = new ConsoleHandler();
    handler.setLevel(Level.ALL);
    Logger log = LogManager.getLogManager().getLogger("");
    log.addHandler(handler);
    log.setLevel(Level.ALL);
    System.setProperty("javax.net.debug","all"); 
}
Lonzak
  • 9,334
  • 5
  • 57
  • 88
0

Use something like tcpdump, which can dump the actual network packets that are emitted or received by your computer.

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40
0

On JDK 11 I was able to log all the http connections, setting java.util.logging.ConsoleHandler.level to FINEST and adding the following lines in the file logging.properties which is by default in %JAVA_HOME%/conf:

sun.net.www.protocol.http.HttpURLConnection.level = FINEST
sun.net.www.protocol.http.HttpURLConnection.handlers = java.util.logging.ConsoleHandler
Stefano Curcio
  • 375
  • 3
  • 11