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();
しかし、私の文字列は空です。 私は何が間違っていますか?単純な文字列やオブジェクトを受け取るようにサーバー/クライアントを変更するにはどうすればよいですか?おかげさまで
最後のリストで "接続" とは何ですか? –
これはクライアントで開いたのと同じ接続です(このセクションをクライアントに追加したばかりです)。 – SHAI