2013-09-27 19 views
6

Sto tentando di effettuare chiamate di servizio di riposo in Java. Sono nuovo del web e del servizio di riposo. Ho un servizio di riposo che restituisce json come risposta. Ho il seguente codice ma penso che sia incompleto perché non so come elaborare l'output usando json.Ottenere risposta JSON come parte di Rest call in Java

public static void main(String[] args) { 
     try { 

      URL url = new URL("http://xyz.com:7000/test/db-api/processor"); 
      HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoOutput(true); 
      connection.setInstanceFollowRedirects(false); 
      connection.setRequestMethod("PUT"); 
      connection.setRequestProperty("Content-Type", "application/json"); 

      OutputStream os = connection.getOutputStream(); 
      //how do I get json object and print it as string 
      os.flush(); 

      connection.getResponseCode(); 
      connection.disconnect(); 
     } catch(Exception e) { 
      throw new RuntimeException(e); 
     } 

    } 

prega di aiuto. Sono nuovo ai servizi di riposo e JSON. Grazie mille in anticipo.

+0

Se si utilizza Primavera, si rende la vita facile. Eseguirà una richiesta HTTP, convertirà la risposta HTTP in un tipo di oggetto di tua scelta e restituirà quell'oggetto. https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate –

risposta

2

Poiché si tratta di una richiesta PUT vi state perdendo un paio di cose qui:

OutputStream os = conn.getOutputStream(); 
os.write(input.getBytes()); // The input you need to pass to the webservice 
os.flush(); 
... 
BufferedReader br = new BufferedReader(new InputStreamReader(
     (conn.getInputStream()))); // Getting the response from the webservice 

String output; 
System.out.println("Output from Server .... \n"); 
while ((output = br.readLine()) != null) { 
    System.out.println(output); // Instead of this, you could append all your response to a StringBuffer and use `toString()` to get the entire JSON response as a String. 
    // This string json response can be parsed using any json library. Eg. GSON from Google. 
} 

Dai un'occhiata alla this per avere un'idea più chiara su colpire webservices.

0

Dal momento che il Content-Type è application/json, potresti lanciare direttamente la risposta a un oggetto JSON per esempio

JSONObject recvObj = new JSONObject(response); 
2

Il codice è in gran parte corretto, ma non v'è errore su OutputStream. Come R.J ha detto che OutputStream è necessario per passare richiesta corpo al server. Se il tuo servizio di riposo non richiede alcun corpo, non è necessario utilizzarlo.

Per leggere la risposta del server è necessario utilizzare InputStream (R.J si mostrano anche esempio) così:

try (InputStream inputStream = connection.getInputStream(); 
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();) { 
    byte[] buf = new byte[512]; 
    int read = -1; 
    while ((read = inputStream.read(buf)) > 0) { 
     byteArrayOutputStream.write(buf, 0, read); 
    } 
    System.out.println(new String(byteArrayOutputStream.toByteArray())); 
} 

In questo modo è buono se non si vuole dipende da librerie di terze parti. Quindi ti consiglio di dare un'occhiata a Jersey - una libreria molto bella con una quantità enorme di funzionalità molto utile.

Client client = JerseyClientBuilder.newBuilder().build(); 
    Response response = client.target("http://host:port"). 
      path("test").path("db-api").path("processor").path("packages"). 
      request().accept(MediaType.APPLICATION_JSON_TYPE).buildGet().invoke(); 
    System.out.println(response.readEntity(String.class)); 
-1
JsonKey jsonkey = objectMapper.readValue(new URL("http://echo.jsontest.com/key/value/one/two"), JsonKey.class); 
System.out.println("jsonkey.getOne() : "+jsonkey.getOne()) 
Problemi correlati