2013-09-27 4 views
6

자바로 서비스 요청을하려고합니다. 나는 새로운 웹과 휴식 서비스. 응답으로 json을 반환하는 휴식 서비스가 있습니다. 다음 코드는 있지만 json을 사용하여 출력을 처리하는 방법을 알지 못하므로 불완전하다고 생각합니다.Java에서 Rest call의 일부로 JSON 응답 받기

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

    } 

도와주세요. 나는 새로운 서비스와 json입니다. 많은 감사드립니다.

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

가 웹 서비스를 타격에 좀 더 명확한 아이디어를 가지고 this에서보세요 :이 이후

+0

, 그것은 당신의 인생을 쉽게. HTTP 요청을 수행하고 HTTP 응답을 원하는 객체 유형으로 변환 한 다음 해당 객체를 반환합니다. https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate –

답변

2

당신이 여기 몇 가지를 놓치고 PUT 요청입니다. 귀하의 콘텐츠 형식이 응용 프로그램/JSON이기 때문에

0

, 당신은 직접

JSONObject recvObj = new JSONObject(response); 
2

귀하의 코드는 대부분 정확 예를 들어, JSON 객체에 대한 응답을 캐스팅 할 수 있지만 실수에 대한 OutputStream이있다. R.J는 요청 요청을 서버에 전달하는 데 OutputStream이 필요하다고 말했습니다. 휴식 서비스에 어떤 신체가 필요하지 않으면이 서비스를 사용할 필요가 없습니다. 당신이 세 번째 부분 라이브러리에 의존하지 않으려는 경우

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

이 방법이 좋다 : 서버 응답을 읽기 위해

당신은 그렇게 InputStream (R.J도 보여 예)를 사용합니다. 그래서 Jersey을 살펴 보는 것이 좋습니다. 매우 유용한 라이브러리로 매우 유용한 라이브러리입니다. 당신은 스프링을 사용하는 경우

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