2013-09-27 17 views
6

Java'da dinlenme hizmeti araması yapmaya çalışıyorum. Web ve dinlenme hizmetinde yeniyim. Yanıt olarak jsonu döndüren dinlenme servisim var. Aşağıdaki koda sahibim ama eksik olduğunu düşünüyorum çünkü json kullanarak çıktının nasıl işleneceğini bilmiyorum.Java'da Rest çağrısının bir parçası olarak JSON yanıtı alma

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); 
     } 

    } 

Lütfen yardım edin. Dinlenme hizmetleri ve json için yeniyim. Şimdiden çok teşekkürler.

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. 
} 

webservices isabet üzerinde daha net fikir sahibi olmak this göz at: Bu yana

+0

, bu hayatınızı kolaylaştırır. Bir HTTP isteği gerçekleştirecek, HTTP yanıtını seçtiğiniz bir nesne türüne dönüştürecek ve bu nesneyi döndürecektir. https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate –

cevap

2

burada bir kaç şey kaçırdığınızı bir PUT talebidir. İçerik-Tipi uygulama/json olduğundan

0

doğrudan

JSONObject recvObj = new JSONObject(response); 
2

Kodunuz çoğunlukla doğrudur örneğin bir JSON nesnesine yanıtı döküm olabilir, ama hata yaklaşık OutputStream yoktur. R.J'nin OutputStream belirtildiği gibi, istemcisini sunucuya iletmek için gövdesini istemesi gerekir. Dinlenme servisiniz herhangi bir vücut gerektirmiyorsa, bunu kullanmanıza gerek yoktur. Eğer üçüncü bölümü kütüphaneleri bağlıdır istemiyorsanız

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())); 
} 

Bu şekilde iyidir: Sunucu yanıtı okumak için

böyle InputStream (R.J. da göstermek örnek) kullanmak gerekir. Bu yüzden, Jersey'a bir göz atmanızı öneriyorum - çok kullanışlı bir özellik olan çok güzel bir kütüphane. Eğer bahar kullanıyorsanız

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())