Java Http POST with basic authorization and redirect

巧了我就是萌 提交于 2020-01-04 01:48:26

问题


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()));


来源:https://stackoverflow.com/questions/6038415/java-http-post-with-basic-authorization-and-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!