2016-02-25 17 views
-1

我想從REST API獲取JSON數據。如何從休息API獲取JSON數據

我寫了一個簡單的Java類作爲Jersey客戶端連接到Web服務,但是當我執行這個類時,他顯示的是HTML而不是JSON。 知道API是使用登錄名和密碼進行身份驗證的,我不知道如何處理。 這是我試圖編寫的類的源代碼。

{ 
    public class RestClient { 

    public static void main(String ar[]) throws Exception 
    { 

     String baseUrl="??????????????"; 
     String password="???????????"; 
     String user="?????????";  

     ClientConfig config = new DefaultClientConfig(); 
     Client client = Client.create(config); 

     WebResource service = client.resource(baseUrl); 
     service.path("j_spring_security_check"); 
     service.queryParam("j_username", user); 
     service.queryParam("j_password", user); 
     service.queryParam("ajax", "true"); 
     String out = service.accept(MediaType.APPLICATION_JSON).get(String.class); 
     System.out.println(out); 
    } 
} 
+0

這將取決於,至少部分,在你試圖正是休息API與你交談,你忽略分享。 –

+0

謝謝@Scott Hunter,它是一個API公司所有者,我試圖建立一個客戶球衣 API實現基本認證 –

+0

我不明白是連接參數,我應該在頭部發送(queryparams() )還是有另一種解決方案 –

回答

0

正如其他人說它取決於REST API。你是代碼看起來o.k.但也許嘗試使用下面的代碼,並插入查詢參數到URL 像這樣:/ parmam1 =值&參數2 =值2

Client client = Client.create(); 
WebResource webResource = client.resource(url); 
String jsonResult = webResource.accept("application/json").get(ClientResponse.class).getEntity(String.class); 
+0

謝謝@Tal Joffe,我問你如何在代碼中使用基本身份驗證客戶端 –

+0

,它看起來像通過查詢參數使用身份驗證,在這種情況下我的示例工作。 如果你有更復雜的東西試試這個http://stackoverflow.com/questions/6774506/jersey-client-api-authentication –