Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Display request of an HttpURLConnection before sending

Tags:

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

like image 596
Hirnhamster Avatar asked Aug 06 '10 22:08

Hirnhamster


People also ask

How do I get HttpURLConnection response code?

Set the request method in HttpURLConnection instance, default value is GET. Call setRequestProperty() method on HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc. We can call getResponseCode() to get the response HTTP code.

How do I get HttpURLConnection cookies?

Retrieving CookiesCreate an instance of the CookieManager class and set its CookiePolicy . Set this instance of the CookieManager as the default CookieHandler . Open a URLConnection to the website of your choice. Next, retrieve cookies from the underlying CookieStore by using the getCookies method.

What is the difference between URLConnection and HttpURLConnection?

URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.


2 Answers

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 
like image 181
RealHowTo Avatar answered Apr 28 '23 03:04

RealHowTo


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.

like image 35
Mike Baranczak Avatar answered Apr 28 '23 03:04

Mike Baranczak