gpt4 book ai didi

java - 如何使用 OKHTTP 发出 post 请求?

转载 作者:IT老高 更新时间:2023-10-28 11:52:39 29 4
gpt4 key购买 nike

我阅读了一些将 json 发布到服务器的示例。

有人说:

OkHttp is an implementation of the HttpUrlConnection interface provided by Java. It provides an input stream for writing content and doesn't know (or care) about what format that content is.

现在我想用名称和密码参数向 URL 发一个普通的帖子。

这意味着我需要自己将名称和值对编码到流中?

最佳答案

根据 the docs , OkHttp 版本 3 将 FormEncodingBuilder 替换为 FormBodyFormBody.Builder(),因此旧示例将不再适用。

Form and Multipart bodies are now modeled. We've replaced the opaqueFormEncodingBuilder with the more powerful FormBody andFormBody.Builder combo.

Similarly we've upgraded MultipartBuilder intoMultipartBody, MultipartBody.Part, and MultipartBody.Builder.

因此,如果您使用的是 OkHttp 3.x,请尝试以下示例:

OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormBody.Builder()
.add("message", "Your message")
.build();
Request request = new Request.Builder()
.url("https://www.example.com/index.php")
.post(formBody)
.build();

try {
Response response = client.newCall(request).execute();

// Do something with the response.
} catch (IOException e) {
e.printStackTrace();
}

关于java - 如何使用 OKHTTP 发出 post 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23456488/

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