How to use OKHTTP to make a post request?

后端 未结 13 1051
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 05:06

I read some examples which are posting jsons to the server.

some one says :

OkHttp is an implementation of the HttpUrlConnection interface p

相关标签:
13条回答
  • 2020-12-02 05:53

    As per the docs, OkHttp version 3 replaced FormEncodingBuilder with FormBody and FormBody.Builder(), so the old examples won't work anymore.

    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.

    So if you're using OkHttp 3.x try the following example:

    OkHttpClient client = new OkHttpClient();
    
    RequestBody formBody = new FormBody.Builder()
            .add("message", "Your message")
            .build();
    Request request = new Request.Builder()
            .url("http://www.foo.bar/index.php")
            .post(formBody)
            .build();
    
    try {
        Response response = client.newCall(request).execute();
    
        // Do something with the response.
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    0 讨论(0)
提交回复
热议问题