从Java服务器到客户端接收字符串
我有一个java客户端,它将JSON对象发送到服务器(REST服务)。 代码工作得很完美。我当前的服务器返回“RESPONSE”,但我想修改我的代码,将字符串从服务器返回到客户端(类似于“transfer was OK”)——除了将对象从客户端发送到服务器之外。 这是我的密码 服务器:从Java服务器到客户端接收字符串,java,json,rest,stream,inputstream,Java,Json,Rest,Stream,Inputstream,我有一个java客户端,它将JSON对象发送到服务器(REST服务)。 代码工作得很完美。我当前的服务器返回“RESPONSE”,但我想修改我的代码,将字符串从服务器返回到客户端(类似于“transfer was OK”)——除了将对象从客户端发送到服务器之外。 这是我的密码 服务器: @Path("/w") public class JSONRESTService { @POST @Path("/JSONService") @Consumes(MediaType.APPLICATION_JSO
@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();
但是我的字符串是空的。
我做错了什么?我应该如何修改我的服务器/客户机以接收一个简单的字符串,甚至一个对象?
谢谢。您的代码(示例):
上一个清单中的“连接”是什么?它与我在客户端上打开的连接相同(我刚刚将此部分添加到客户端)。嘿,感谢这个示例,它看起来与我所做的类似,但不起作用。我还需要我的客户端上的输入和输出流。所以还不清楚我是否需要一个新的连接?(一个用于outputstream,一个用于inputstream?)@SHAI替换了该示例。我想你需要一个连接。我希望它能起作用。谢谢!我发现了我的问题,而您的代码确实有所帮助-这是我的客户端中的while循环-while(in.readLine()!=null)。我需要写-while(line=in.readLine()!=null)。我只需要更换这条线路,是的,一个连接。
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();
}
}
}