gpt4 book ai didi

java - 使用java中的HttpPost客户端将http post请求发送到带有查询字符串的URL

转载 作者:太空宇宙 更新时间:2023-11-04 14:09:29 25 4
gpt4 key购买 nike

我需要向 url 发送一个 post 请求,其格式如下:

www.abc.com/service/postsomething?data={'name':'rikesh'}&id=45

在java中使用HttpPost客户端,如何将请求发布到这样的查询字符串我可以通过 ajax 轻松地从 javascript 连接,但从 java 客户端连接失败。

(我知道在发布请求中发送查询字符串是愚蠢的想法。由于我正在连接到其他人的服务器,所以我不能不改变它的方式)

最佳答案

这是使用 Java(无需 Apache 库)在 POST 请求中发送 JSON 的一种方法。您可能会发现这很有帮助:

//init
String json = "{\"name\":\"rikesh\"}";
String requestString = "http://www.example.com/service/postsomething?id=45";

//send request
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
os.flush();
int responseCode = conn.getResponseCode();

//get result if there is one
if(responseCode == 200) //HTTP 200: Response OK
{
String result = "";
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while((output = br.readLine()) != null)
{
result += output;
}
System.out.println("Response message: " + result);
}

关于java - 使用java中的HttpPost客户端将http post请求发送到带有查询字符串的URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28501812/

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