2017-02-06 40 views
0

JSONオブジェクトをサーバー(RESTサービス)に送信するJavaクライアントがあります。 コードは完璧に機能します。私の現在のサーバは "RESPONSE"を返しますが、サーバからクライアントへ文字列を返すようにコードを修正したいのです(クライアントからサーバへのオブジェクトの送信に加えて、 "転送OK"のようなもの)。 これは私が持っているコードですJavaサーバーからクライアントへの文字列の受け取り

サーバー:

@Path("/w") 
public class JSONRESTService { 
@POST 
@Path("/JSONService") 
@Consumes(MediaType.APPLICATION_JSON) 
public Response JSONREST(InputStream incomingData) { 
    StringBuilder JSONBuilder = new StringBuilder(); 
    try { 
     BufferedReader in = new BufferedReader(new InputStreamReader(incomingData)); 
     String line = null; 
     while ((line = in.readLine()) != null) { 
      JSONBuilder.append(line); 
     } 
    } catch (Exception e) { 
     System.out.println("Error Parsing: - "); 
    } 
    System.out.println("Data Received: " + JSONBuilder.toString()); 

    // return HTTP response 200 in case of success 
    return Response.status(200).entity(JSONBuilder.toString()).build(); 
} 
} 

クライアント:

私は最初の方法を変更したので、クライアント - サーバーへの文字列を返すために
public class JSONRESTServiceClient { 
public static void main(String[] args) { 
    String string = ""; 
    try { 

     JSONObject jsonObject = new JSONObject("string"); 

     // Step2: Now pass JSON File Data to REST Service 
     try { 
      URL url = new URL("http://localhost:8080/w/JSONService"); 
      URLConnection connection = url.openConnection(); 
      connection.setDoOutput(true); 
      connection.setRequestProperty("Content-Type", "application/json"); 
      connection.setConnectTimeout(5000); 
      connection.setReadTimeout(5000); 
      OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); 
      out.write(jsonObject.toString()); 
      out.close(); 

      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

      while (in.readLine() != null) { 
      } 
      System.out.println("\nJSON REST Service Invoked Successfully.."); 
      in.close(); 
     } catch (Exception e) { 
      System.out.println("\nError while calling JSON REST Service"); 
      System.out.println(e); 
     } 

     br.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
} 

サーバーに文字列を返すには とクライアントにこれを追加しました:

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
StringBuffer sb = new StringBuffer(""); 
String line=""; 
while (in.readLine() != null) { 
       sb.append(line); 
       break; 
      } 
    System.out.println("message from server: " + sb.toString()); 
    in.close(); 

しかし、私の文字列は空です。 私は何が間違っていますか?単純な文字列やオブジェクトを受け取るようにサーバー/クライアントを変更するにはどうすればよいですか?おかげさまで

+0

最後のリストで "接続" とは何ですか? –

+0

これはクライアントで開いたのと同じ接続です(このセクションをクライアントに追加したばかりです)。 – SHAI

答えて

1

あなたのコード(例):

package com.javacodegeeks.enterprise.rest.javaneturlclient; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

public class JavaNetURLRESTFulClient { 

    private static final String targetURL = "http://localhost:8080/w/JSONService"; 

    public static void main(String[] args) { 

     try { 

      URL targetUrl = new URL(targetURL); 

      HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection(); 
      httpConnection.setDoOutput(true); 
      httpConnection.setRequestMethod("POST"); 
      httpConnection.setRequestProperty("Content-Type", "application/json"); 

      String input = "{\"id\":1,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}"; 

      OutputStream outputStream = httpConnection.getOutputStream(); 
      outputStream.write(input.getBytes()); 
      outputStream.flush(); 

      if (httpConnection.getResponseCode() != 200) { 
       throw new RuntimeException("Failed : HTTP error code : " 
        + httpConnection.getResponseCode()); 
      } 

      BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
        (httpConnection.getInputStream()))); 

      String output; 
      System.out.println("Output from Server:\n"); 
      while ((output = responseBuffer.readLine()) != null) { 
       System.out.println(output); 
      } 

      httpConnection.disconnect(); 

      } catch (MalformedURLException e) { 

      e.printStackTrace(); 

      } catch (IOException e) { 

      e.printStackTrace(); 

     } 

     }  
    } 
+0

この例のおかげで、それは私がやったのと似ていますが、うまくいきませんでした。私はまた、私のクライアント上で入力と出力の両方のストリームが必要です。それでは、私は新しい接続が必要かどうかはまだ分かりません。 (1つは出力ストリーム用、もう1つは入力ストリーム用) – SHAI

+0

@SHAIこの例を置き換えました。私は1つの接続が必要だと思います。私はそれがうまくいくことを望む。 –

+0

ありがとう!私の問題を発見し、あなたのコードが助けてくれました。クライアント(while.readLine()!= null)のwhileループでした。私はwrite- while(line = in.readLine()!= null)を書く必要がありました。私はこの行を変更するだけで、1つの接続を変更する必要がありました。 – SHAI

関連する問題