我阅读了一些将 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
替换为 FormBody
和 FormBody.Builder()
,因此旧示例将不再适用。
Form and Multipart bodies are now modeled. We've replaced the opaque
FormEncodingBuilder
with the more powerfulFormBody
andFormBody.Builder
combo.Similarly we've upgraded
MultipartBuilder
intoMultipartBody
,MultipartBody.Part
, andMultipartBody.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/