2016-09-27 67 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“位置:”首标。