7

Javaで残りのサービスを呼び出そうとしています。私はウェブとレストサービスが初めてです。json を応答として返す残りのサービスがあります。次のコードがありますが、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が初めてです。よろしくお願いします。

4

4 に答える 4

3

これは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 サービスをヒットすることについてより明確な考えを持ってください。

于 2013-09-27T08:26:24.567 に答える
2

あなたのコードはほとんど正しいですが、 については間違いがありOutputStreamます。RJが言ったように、リクエスト本文をサーバーOutputStreamに渡す必要があります。残りのサービスがボディを必要としない場合は、これを使用する必要はありません。

サーバーの応答を読み取るには、次のように使用する必要がありますInputStream(RJも例を示します):

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

サードパーティのライブラリに依存したくない場合は、この方法が適しています。だから私はジャージーを見てみることをお勧めします- 膨大な量の非常に便利な機能を備えた非常に素晴らしいライブラリです。

    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));
于 2016-10-06T16:32:20.687 に答える
0

Content-Type は application/json であるため、たとえば、応答を JSON オブジェクトに直接キャストできます。

JSONObject recvObj = new JSONObject(response);
于 2014-01-04T18:58:02.657 に答える