2015-04-01 41 views
0
public class RestClient { 

    public static void main(String[] args) { 
    try { 
     JSONObject jsonObject = new JSONObject(); 
     jsonObject.put("fromSku","NONE"); 
     jsonObject.put("toSku","ASA5500-ENCR-K8"); 
     jsonObject.put("modelNo", "ASAV10"); 
     jsonObject.put("serialNo", "ASATSTSN"); 
     System.out.println(jsonObject); 

     URL url = new URL("http://licruleswb-    dev.cloudapps.cisco.com/LicenseRules/rest/invokeASARule"); 

     URLConnection connection = url.openConnection(); 
     connection.setDoOutput(true); 

     String encodedCredentials = new String(
        org.apache.commons.codec.binary.Base64.encodeBase64 
        (org.apache.commons.codec.binary.StringUtils.getBytesUtf8("username:password")) 
        ); 

      System.out.println(encodedCredentials); 
      connection.setRequestProperty ("Authorization", encodedCredentials); 
      connection.setRequestProperty("Content-Type", "application/json"); 
      connection.setConnectTimeout(5000); 
      connection.setReadTimeout(5000); 
      OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); 
      out.write(jsonObject.toString()); 
      out.close(); 

      BufferedReader in = new BufferedReader(new InputStreamReader(
        connection.getInputStream())); 

      System.out.println(in.toString()); 
      while (in.readLine() != null) { 
       System.out.println(in.readLine()); 
      } 
      System.out.println("\nREST Service Invoked Successfully.."); 
      in.close(); 
     } catch (Exception e) { 
      System.out.println("\nError while calling REST Service"); 
      System.out.println(e); 
     } 



    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 

    } 
} 

輸出:Java程序調用REST服務需要認證

<html><head> 
</head><body> 
<p>The document has moved <a href="https://wwwin-sso-nprd.cisco.com/obrareq.cgi?wh%3Dlicruleswbintrtpdev-licensingrules.cloudapps.cisco.com%20wu%3D%2FLicenseRules%2Frest%2FinvokeASARule%20wo%3D2%20rh%3Dhttp%3A%2F%2Flicruleswb-dev.cloudapps.cisco.com%20ru%3D%252FLicenseRules%252Frest%252FinvokeASARule">here</a>.</p> 
null 

REST Service Invoked Successfully.. 

誰能幫我解決這個問題。如果在REST客戶端廣告中使用此鏈接,那麼這個鏈接工作得非常好。但是,對於這個Java程序,它會拋出302錯誤。

+0

服務器響應重定向。如果你想用'url.openConnection()'自己實現它,你必須編寫代碼來處理它 - 或者使用類似apache httpclient的東西,這使得它更容易:http://hc.apache.org /httpclient-3.x/順便說一句:302不是錯誤! – Alexander 2015-04-01 07:39:37

+0

好吧..我也嘗試過使用HttpClient,但也有身份驗證沒有發生,並將401身份驗證失敗作爲響應。你能幫我解決這個問題嗎? – user3564975 2015-04-03 06:34:26

回答

0

我在嘗試類似的東西時遇到了你的線程。對我來說,通過將「Basic」與encodedCredentials變量連接在一起解決了問題,使其成爲「Basic EncodedValue」。

相關問題