2015-04-28 45 views
-2

我想從雲數據中獲取對字符串變量的響應。如何從雲到字符串獲取響應數據

ClientResource cr = new ClientResource("http://localhost:8888/users"); 
cr.setRequestEntityBuffering(true); 
try { 
    try { 
     cr.get(MediaType.APPLICATION_JSON).write(System.out); 
    } catch (IOException e) { 

     e.printStackTrace(); 
    } 
} catch (ResourceException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

我有響應,JSON在控制檯中,我想將其轉換爲字符串,則該GSON庫將是有益的?我還沒有使用它。我需要在代碼中進行哪些修改?任何人都可以幫助我。

回答

0

事實上,的Restlet接收響應有效載荷爲字符串,您可以直接訪問這個,如下所述:

ClientResource cr = new ClientResource("http://localhost:8888/users"); 
cr.setRequestEntityBuffering(true); 

Representation representation = cr.get(MediaType.APPLICATION_JSON); 
String jsonContentAsString = representation.getText(); 

希望它可以幫助你, Thierry

+0

是的,我已經得到了答案,反正謝謝很多蒂埃裏:) –

0

下面是一個工作示例:

try { 

      URL url = new URL("http://localhost:8888/users"); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setRequestMethod("GET"); 
      conn.setRequestProperty("Accept", "application/json"); 

      if (conn.getResponseCode() != 200) { 
       throw new RuntimeException("Failed : HTTP error code : " 
         + conn.getResponseCode()); 
      } 

      BufferedReader br = new BufferedReader(new InputStreamReader(
       (conn.getInputStream()))); 

      String output; 
      System.out.println("Raw Output from Server .... \n"); 
      while ((output = br.readLine()) != null) { 
       System.out.println(output); 
      } 

      conn.disconnect(); 

      } catch (MalformedURLException e) { 

      e.printStackTrace(); 

      } catch (IOException e) { 

      e.printStackTrace(); 

      } 

    } 
相關問題