2016-09-27 193 views
2

我試圖讓這個代碼塊運行,但我不斷收到一個302我試圖顯示代碼的流程。我只是不知道什麼是錯的。Java的HttpURLConnection的狀態碼302

import java.net.HttpURLConnection; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.Base64; 

public class AuthenticateLoginLogoutExample { 


public static void main(String[] args) throws Exception { 
    new AuthenticateLoginLogoutExample().authenticateLoginLogoutExample(
        "http://" + Constants.HOST + "/qcbin", 
        Constants.DOMAIN, 
        Constants.PROJECT, 
        Constants.USERNAME, 
        Constants.PASSWORD); 
} 

public void authenticateLoginLogoutExample(final String serverUrl, 
     final String domain, final String project, String username, 
     String password) throws Exception { 

    RestConnector con = 
      RestConnector.getInstance().init(
        new HashMap<String, String>(), 
        serverUrl, 
        domain, 
        project); 

    AuthenticateLoginLogoutExample example = 
     new AuthenticateLoginLogoutExample(); 

    //if we're authenticated we'll get a null, otherwise a URL where we should login at (we're not logged in, so we'll get a URL). 

它是在isAuthenticated()方法開始時的下一行。當年這裏

public String isAuthenticated() throws Exception { 

    String isAuthenticateUrl = con.buildUrl("rest/is-authenticated"); 
    String ret; 

在這下一行試圖得到響應:

String authenticationPoint = example.isAuthenticated(); 
    Assert.assertTrue("response from isAuthenticated means we're authenticated. that can't be.", authenticationPoint != null); 

    //do a bunch of other stuff 
} 

於是我們進入isAuthenticated方法。 con.httpGet

Response response = con.httpGet(isAuthenticateUrl, null, null); 
    int responseCode = response.getStatusCode(); 

    //if already authenticated 
    if (responseCode == HttpURLConnection.HTTP_OK) { 

     ret = null; 
    } 

    //if not authenticated - get the address where to authenticate 
    // via WWW-Authenticate 
    else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { 

     Iterable<String> authenticationHeader = 
       response.getResponseHeaders().get("WWW-Authenticate"); 

     String newUrl = 
      authenticationHeader.iterator().next().split("=")[1]; 
     newUrl = newUrl.replace("\"", ""); 
     newUrl += "/authenticate"; 
     ret = newUrl; 
    } 

    //Not ok, not unauthorized. An error, such as 404, or 500 
    else { 

     throw response.getFailure(); 
    } 

    return ret; 
} 

跳轉我們帶到另一個階級和進入這個方法:

public Response httpGet(String url, String queryString, Map<String, 
     String> headers)throws Exception { 

    return doHttp("GET", url, queryString, null, headers, cookies); 
} 

的doHttp把我們這裏。 type =「GET」,url =「http://SERVER/qcbin/rest/is-authenticated」,其餘全部爲空。

private Response doHttp(
     String type, 
     String url, 
     String queryString, 
     byte[] data, 
     Map<String, String> headers, 
     Map<String, String> cookies) throws Exception { 

    if ((queryString != null) && !queryString.isEmpty()) { 

     url += "?" + queryString; 
    } 

    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); 

    con.setRequestMethod(type); 
    String cookieString = getCookieString(); 

    prepareHttpRequest(con, headers, data, cookieString); 

下一行的con.connect()從不連接。

con.connect(); 
    Response ret = retrieveHtmlResponse(con); 

    updateCookies(ret); 

    return ret; 
} 

的prepareHttpRequest代碼:

private void prepareHttpRequest(
     HttpURLConnection con, 
     Map<String, String> headers, 
     byte[] bytes, 
     String cookieString) throws IOException { 

    String contentType = null; 

    //attach cookie information if such exists 
    if ((cookieString != null) && !cookieString.isEmpty()) { 

     con.setRequestProperty("Cookie", cookieString); 
    } 

    //send data from headers 
    if (headers != null) { 

     //Skip the content-type header - should only be sent 
     //if you actually have any content to send. see below. 
     contentType = headers.remove("Content-Type"); 

     Iterator<Entry<String, String>> 
      headersIterator = headers.entrySet().iterator(); 
     while (headersIterator.hasNext()) { 
      Entry<String, String> header = headersIterator.next(); 
      con.setRequestProperty(header.getKey(), header.getValue()); 
     } 
    } 

    // If there's data to attach to the request, it's handled here. 
    // Note that if data exists, we take into account previously removed 
    // content-type. 
    if ((bytes != null) && (bytes.length > 0)) { 

     con.setDoOutput(true); 

     //warning: if you add content-type header then you MUST send 
     // information or receive error. 
     //so only do so if you're writing information... 
     if (contentType != null) { 
      con.setRequestProperty("Content-Type", contentType); 
     } 

     OutputStream out = con.getOutputStream(); 
     out.write(bytes); 
     out.flush(); 
     out.close(); 
    } 
} 

而且getCookieString方法:

public String getCookieString() { 

    StringBuilder sb = new StringBuilder(); 

    if (!cookies.isEmpty()) { 

     Set<Entry<String, String>> cookieEntries = 
      cookies.entrySet(); 
     for (Entry<String, String> entry : cookieEntries) { 
      sb.append(entry.getKey()).append("=").append(entry.getValue()).append(";"); 
     } 
    } 

    String ret = sb.toString(); 

    return ret; 
} 

沒有人有任何想法是什麼出了問題?我不知道爲什麼它一直返回一個302

編輯:根據要求添加鉻顯影劑圖像。 enter image description here

+0

的可能的複製[Android的HttpURLConnection類:處理HTTP重定向](HTTP://計算器。com/questions/15754633/android-httpurlconnection-handle-http-redirects) –

+0

@SvetlinZarev - 這是試圖通過REST連接到HP ALM。 –

+0

REST是一種架構風格,因此您無法通過REST進行連接。你在做什麼是一個HTTP調用,並且鏈接的SO問題提供了答案 –

回答

2

我沒有跟着你的整個代碼,但HTTP 302意味着重定向 https://en.wikipedia.org/wiki/HTTP_302

根據的重定向,能夠順利或不能工作。例如有一天,我面對一個http重定向https,我必須解決它手動檢查位置標題。

我會做的是首先要檢查頭在瀏覽器,Chrome瀏覽器去開發工具,網絡和檢查響應頭(截圖)。您應該在302處看到位置標題,並附帶您應遵循的新網址。

enter image description here

+0

當我手動輸入網址並訪問網站時,我發現我多次收到安全警告對話框。任何想法如何處理這些編程? –

+0

當你說「手動」時,你的意思是用瀏覽器,對吧?如果您的Java代碼獲得302,那麼它並不關心您的瀏覽器正在查找的安全問題。 – LinuxDisciple

+0

如果您可以將這些屏幕截圖添加到您的問題中,將會很有幫助。但是我首先要做的是在瀏覽器中執行請求,並檢查那裏的標題。我編輯了我的答案檢查出來。 – psabbate

0

302意味着有一個頁面有,但你真的想要一個不同的頁面(或你想要這個頁面,然後其他的頁面)。如果您查看從服務器返回的標題,那麼您可能會找到一個「位置:」標題,告訴您接下來要查詢的位置,然後您必須編寫另一個事務。

瀏覽器解釋該302響應並自動重定向到指定的URL「位置:」首標。