How to use OKHTTP to make a post request?

后端 未结 13 1070
佛祖请我去吃肉
佛祖请我去吃肉 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:30

    You can make it like this:

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, "{"jsonExample":"value"}");
    
        OkHttpClient client = new OkHttpClient();
    
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Authorization", "header value") //Notice this request has header if you don't need to send a header just erase this part
                .build();
    
        Call call = client.newCall(request);
    
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
    
                Log.e("HttpService", "onFailure() Request was: " + request);
    
                e.printStackTrace();
            }
    
            @Override
            public void onResponse(Response r) throws IOException {
    
                response = r.body().string();
    
                Log.e("response ", "onResponse(): " + response );
    
            }
        });
    

提交回复
热议问题