Joe C
Joe C

Reputation: 21

Programmatically POST to ASP type WEBPAGE

I have been toiling over HttpURLConnection and setRequestProperty for 2 days so far and I cannot get this webpage to Post and return the page I desire. This is what I have so far...

... String data = URLEncoder.encode("acctno", "UTF-8") + "=" + URLEncoder.encode("1991462", "UTF-8");

    URL oracle = new URL("http://taxinquiry.princegeorgescountymd.gov");
    HttpURLConnection yc = (HttpURLConnection) oracle.openConnection();
    yc.setRequestMethod("POST");

    yc.setRequestProperty("Content-Type", "text/html; charset=utf-8");
    yc.setRequestProperty("Content-Length", "19004");
    yc.setRequestProperty("Cache-Control", "private");
    yc.setRequestProperty("Set-Cookie", "ASP.NET_SessionId=v5rdm145zv3jm545kdslgz55; path=/");
    yc.setRequestProperty("X-AspNet-Version", "1.1.4322");
    yc.setRequestProperty("X-Powered-By", "ASP.NET");
    yc.setRequestProperty("Server", "Microsoft-IIS/6.0");

    yc.setDoOutput(true);
    yc.setDoInput(true);

    OutputStreamWriter out = new OutputStreamWriter(yc.getOutputStream());

    out.write(data);
    out.flush();
    //out.write(data);
    out.close();
    ...

It returns the same page defined in URL. it doesn't send me the requested page which should have an ending /taxsummary.aspx

It looks as if the asp takes the post data and generates an HTML unique for each parameter given. How do I give it the correct parameters?

Upvotes: 0

Views: 180

Answers (1)

AlexR
AlexR

Reputation: 115388

Your code looks fine. I believe it sends POST correctly. I think that the problem is not here. When you are using browser you first perform at least one HTTP GET to arrive to the form. When you are doing this the server creates HTTP session for you and returns its id in response header Set-Cookie. When you are submitting the form using browser it sends this header (Cookie) back, so the server can identify the session.

When you are working from java you are skipping the first phase (HTTP GET). So the first thing you are doing is POST while you do not have session yet. I do not know what is the logic of this ASP page but I think that it just rejects such requests.

So, first check this guess. You can use plugin to Firefox named LiveHttpHeaders. Install it and perform the operation manually. You will see all HTTP requests and responses. Save them. Check that the session ID is sent back from server to client. Now implement exactly the same in java.

BTW often the situation is event more complicated when server sends multiple redirect responses. Int this case you have to follow them. HttpConnection has method setFollowRedirects(). Call it with parameter true.

BTW2: Apache HttpClient is a perfect replacement to HttpConnection. it does everything and is very recommended when you are implementing such tasks.

That's all. Good luck. Sometimes it is not easy...

Upvotes: 2

Related Questions