2017-05-23 56 views
0

打REST服務時,在同一地址登錄我打剩下的URL無法用java

https://db2adminpc1:9443/rest/bpm/wle/v1/search/query?organization=byInstance&run=true&shared=false&filterByCurrentUser=true 

使用HttpURLConnection的類和我的InputStream獲得斯喬數據。

但在我的需求中,當我打開URL時,它應該存儲一些令牌或cookie來在Chrome瀏覽器中打開相同的URL時對URL進行身份驗證。下面 你可以找到代碼:

byte[] encodedBytes = Base64.getEncoder().encode(Data.getBytes()); 

    URL url = new URL(
      "https://db2adminpc1:9443/rest/bpm/wle/v1/search/query?organization=byInstance&run=true&shared=false&filterByCurrentUser=true"); 
    connection = (HttpURLConnection) url.openConnection(); 

    String encoding = new String(encodedBytes);// "cGNhZG1pbjpwY2FkbWlu"; 
    connection.setRequestMethod("POST"); 
    connection.setDoOutput(true); 
    connection.setRequestProperty("Authorization", "Basic " + encoding); 
    connection.getRequestProperty("Set-Cookie"); 

    System.out.println("Session iD " + connection.getHeaderField("Set-Cookie")); 
    System.out.println("Session iD " + connection.getHeaderField("Set-Cookie")); 

    if (connection.getResponseCode() == 200) { 
     InputStream content = (InputStream) connection.getInputStream(); 

     BufferedReader in = new BufferedReader(new InputStreamReader(content)); 

     while ((line = in.readLine()) != null) { 
      // System.out.println(line); 
      sb.append(line); 
     } 
     content.close(); 

    } else { 
     sb.append("\"Username And Password Does Not Match!!!\""); 
    } 

} 

Update I am able read LTPatoken2 but dont know how to put or store in localhost cookie and authenticate the URL

回答

0

因爲HttpURLConnection不保持cookie的,所以你必須在Set-Cookie頭保存到String實例,同時第一次訪問的URL,然後,對每個下一個請求,你應該設置請求頭Cookie通過調用方法setRequestProperty。當然,你可以使用HttpClient庫,它可以自動維護餅乾

+0

我能夠得到的cookie,基本上我調用休息服務使用本地主機到th e WebSphere.And我希望它將cookie存儲到我的WebSphere URL中。 –