2013-09-27 13 views
6

Javaでサービスコールを再開しようとしています。私はウェブとレストサービスに新しいです。私は応答として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を休むことに新しいです。ありがとうございます。

+0

あなたが春を使用している場合、それはあなたの人生が容易になります。 HTTPリクエストを実行し、HTTPレスポンスを任意のオブジェクトタイプに変換し、そのオブジェクトを返します。 https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate –

答えて

2

これはあなたがここにいくつかのことを逃しているPUT要求であるので:

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

は、Webサービスを打つのより明確な考えを持っているthisを見てください。

0

あなたのContent-Typeはアプリケーション/ JSONですので、あなたが直接

JSONObject recvObj = new JSONObject(response); 
2

例えばJSONオブジェクトへの応答を唱えあなたのコードはほとんどが正しいですが、間違いについてOutputStreamがあります。 R.Jは要求ボディをサーバーに渡すにはOutputStreamが必要とされています。 あなたのレストサービスでは身体を必要としない場合は、この身体を使用する必要はありません。

サーバー応答を読み取るためのあなたはInputStreamを使用する必要がありますそのように(R.Jはまた、あなたの例を示した):

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

あなたは三部構成のライブラリに依存したくない場合は、この方法が良いです。だから私は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()) 
関連する問題