java json socket_使用Java通过TCP发送JSON对象

我试图替换在终端中运行的Netcat命令,该命令将重置服务器上的某些数据。netcat命令如下所示:

echo '{"id":1, "method":"object.deleteAll", "params":["subscriber"]} ' | nc x.x.x.x 3994

我一直试图在Java中实现它,因为我希望能够从正在开发的应用程序中调用此命令。我遇到了问题,但命令从未在服务器上执行。

这是我的Java代码:

try {

Socket socket = new Socket("x.x.x.x", 3994);

String string = "{\"id\":1,\"method\":\"object.deleteAll\",\"params\":[\"subscriber\"]}";

DataInputStream is = new DataInputStream(socket.getInputStream());

DataOutputStream os = new DataOutputStream(socket.getOutputStream());

os.write(string.getBytes());

os.flush();

BufferedReader in = new BufferedReader(new InputStreamReader(is));

String inputLine;

while ((inputLine = in.readLine()) != null)

System.out.println(inputLine);

is.close();

os.close();

} catch (IOException e) {

e.printStackTrace();

}

代码还挂在应读取的while循环上InputStream,我不知道为什么。我一直在使用Wireshark捕获数据包,并且输出的数据看起来是相同的:

{"id":1,"method":"object.deleteAll","params":["subscriber"]}

也许其余的包装袋的形状不同,但我真的不明白为什么会这样。也许我以错误的方式将字符串写到OutputStream?我不知道 :(

编辑:这些是我从运行nc命令中获得的可能结果,如果OutputStream以正确的方式发送正确的数据,我希望将相同的消息发送给InputStream:

错误的论点:

{"id":1,"error":{"code":-32602,"message":"Invalid entity type: subscribe"}}

好的,成功:

{"id":1,"result":100}

没有要删除的内容:

{"id":1,"result":0}

哇,我真的不知道

我尝试了一些不同的作家,例如“缓冲作家”和“印刷作家”,看来这PrintWriter就是解决方案。尽管我无法使用PrintWriter.write()或PrintWriter.print()方法。我不得不用PrintWriter.println()。

如果有人能回答为什么其他作者无法工作的原因,并解释他们将如何影响发送到服务器的数据,那么我很乐意接受这作为解决方案。

try {

Socket socket = new Socket(InetAddress.getByName("x.x.x.x"), 3994);

String string = "{\"id\":1,\"method\":\"object.deleteAll\",\"params\":[\"subscriber\"]}";

DataInputStream is = new DataInputStream(socket.getInputStream());

DataOutputStream os = new DataOutputStream(socket.getOutputStream());

PrintWriter pw = new PrintWriter(os);

pw.println(string);

pw.flush();

BufferedReader in = new BufferedReader(new InputStreamReader(is));

String inputLine;

while ((inputLine = in.readLine()) != null)

System.out.println(inputLine);

is.close();

os.close();

} catch (IOException e) {

e.printStackTrace();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值