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

标签 java okhttp

我阅读了一些将 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 opaque FormEncodingBuilder with the more powerful FormBody and FormBody.Builder combo.

Similarly we've upgraded MultipartBuilder into MultipartBody, 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/

相关文章:

java - 如何在retrofit 2.0中自定义gson转换器?

okhttp - 手动启用验证器

java - 面向对象编程问题

java - 为什么 24 * 60 * 60 * 1000 * 1000 除以 24 * 60 * 60 * 1000 在 Java 中不等于 1000?

java - Java中的DH key 协议(protocol): why generated keys are moSTLy equal for both parties?

java - 如何从控制台上传带有其他数据的文件

android - 如何为 OkHttpClient 设置连接超时? 2017年

java - 写入外部变量时,将内部循环与流并行化

android - 如何在 okhttp3 身份验证器中使用异步请求添加带有刷新 token 的身份验证

java - 改造 2.0.1 添加 cookie header 不起作用