gpt4 book ai didi

java - 从客户端执行 json 远程过程调用(RPC)

转载 作者:行者123 更新时间:2023-12-01 09:20:53 27 4
gpt4 key购买 nike

我正在开发一个java应用程序。我需要调用远程 api 方法。假设我有以下信息:remote_ipremote_portremote_method_name 和一些要发布的key-value 数据。我需要通过 TCP 协议(protocol)将数据发布到远程服务器。我以这种方式测试了Sockets,但不起作用:

Socket socket = new Socket(remote_ip, remote_port);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
String params = URLEncoder.encode("key1", "UTF-8")
+ "=" + URLEncoder.encode(value1, "UTF-8");

params += "&" + URLEncoder.encode("key2", "UTF-8")
+ "=" + URLEncoder.encode(value2, "UTF-8");
wr.write("POST " + remote_method_name + " HTTP/1.0\r\n");
wr.write("Content-Length: " + params.length() + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");

wr.write(params);
wr.flush();

谁能告诉我如何以正确的方式调用api方法?

如果可能的话,我想在没有任何第三方库的情况下完成它。

如有任何帮助,我们将不胜感激。

最佳答案

首先,即使您说您想使用原始 tcp 套接字,但您显然是在尝试发出 HTTP 休息请求。使用 http 客户端会方式更容易、更合适。如果您不想使用第三方库,请使用内置的 HttpUrlConnection ( example usage )。

另一个优点是使用 http 客户端会给你一个清晰的错误消息。

第二,您确定该内容类型吗?如果您尝试提交 json,通常要设置的 header 为 Content-Type: application/json

第三,如果您收到404 not found,我敢打赌您发布的网址不正确。与向您提供此 API 规范的人员仔细检查域和基本 URL。现在您的 URL 基本上是 http://remote_ip:remote_port/remote_method_name这不太可能是正确的。

关于java - 从客户端执行 json 远程过程调用(RPC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40171522/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com