Java Http POST with basic authorization and redire

2019-07-22 04:08发布

问题:

The program does a http post with basic authorization just fine but when the post is complete the page is redirected to a success page. The redirect failes due to 401 authorization failed.

        final URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Authorization", "basic " +base64);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

The line

rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

fails due to 401 authorization failed...

I have also tried adding

conn.setRequestProperty("Authorization", "basic " +base64);

after

wr.flush();

I get the error of "Already connected". Evidently the authorization that I set doesn't follow over to the redirect. Any solutions to this problem is greatly appreciated.

回答1:

You have 2 options you can try:

  1. Use the setDefaultRequestProperty (see http://download.oracle.com/javase/1.5.0/docs/api/java/net/URLConnection.html#setDefaultRequestProperty%28java.lang.String,%20java.lang.String%29) method to set the Authorization header.
  2. Disable automatic redirect following: http://download.oracle.com/javase/1.5.0/docs/api/java/net/HttpURLConnection.html#setInstanceFollowRedirects%28boolean%29 and do it manually.


回答2:

Here is the working solution for anyone else who has this problem. Thanks again to Femi for providing a workaround idea.

URL url = new URL(page);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "basic " +base64);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
if(conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP){
    url = new URL(conn.getHeaderField("Location"));
    conn = (HttpURLConnection)url.openConnection();
    conn.setRequestProperty("Authorization", "basic " +base64);
}
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));