okhttp3用application/json请求

本文介绍了如何使用 OkHttp 发起 GET 和 POST 请求,并详细展示了如何处理带参数的 GET 请求、POST 表单请求以及 Content-Type 为 application/json 的 POST 请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先说下okhttp get请求

                OkHttpClient okHttpClient = new OkHttpClient();
                okhttp3.Request request = new okhttp3.Request.Builder().url(url).build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                        String message = e != null ? e.getMessage() : "";
                        Log.e(TAG, "onFailure: "+message );

                    }

                    @Override
                    public void onResponse(Call call, okhttp3.Response response) throws IOException {

                        String body = response.body().string();
                        Log.e(TAG, "onResponse: body = " + body);

                    }
                });

带参数的okhttp get请求

                final String baseUrl= "http://api.k780.com:88/";
                
                HttpUrl httpUrl = HttpUrl.parse(baseUrl).newBuilder()
                        .addQueryParameter("app","weather.realtime")
                        .addQueryParameter("sign","b59bc3ef6191eb9f747dd4e83c99f2a4")
                        .addQueryParameter("appkey","10003")
                        .addQueryParameter("format", "json")
                        .addQueryParameter("weaId", "1")
                        .build();

                OkHttpClient okHttpClientGetParams = new OkHttpClient();
                okhttp3.Request requestGetParams = new okhttp3.Request.Builder().url(httpUrl.toString()).build();
                okHttpClientGetParams.newCall(requestGetParams).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                        String message = e != null ? e.getMessage() : "";
                        Log.e(TAG, "onFailure: "+message );
                    }

                    @Override
                    public void onResponse(Call call, okhttp3.Response response) throws IOException {

                        String body = response.body().string();
                        Log.e(TAG, "onResponse: body = " + body);
                    }
                });

post form表单请求

                final String baseUrl= "http://api.k780.com:88/";

                RequestBody requestBodyPost = new FormBody.Builder().add("app","weather.realtime")
                        .add("sign","b59bc3ef6191eb9f747dd4e83c99f2a4")
                        .add("appkey","10003")
                        .add("format", "json")
                        .add("weaId", "1").build();

                OkHttpClient okHttpClientPost = new OkHttpClient();
                okhttp3.Request requestPost = new okhttp3.Request.Builder().url(baseUrl).post(requestBodyPost).build();
                okHttpClientPost.newCall(requestPost).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                        String message = e != null ? e.getMessage() : "";
                        Log.e(TAG, "onFailure: "+message );
                    }

                    @Override
                    public void onResponse(Call call, okhttp3.Response response) throws IOException {

                        String body = response.body().string();
                        Log.e(TAG, "onResponse: body = " + body);
                    }
                });

post Content-Type : application/json请求

Content-Typeapplication/json,如下代码修改头文件是没有效果的。

                okhttp3.Request request = new okhttp3.Request.Builder()
                        .url(baseUrl)
                        .addHeader("Content-Type", "application/json")
                        .post(requestBody)
                        .build();

需要使用MediaType.parse("application/json; charset=utf-8"),并且发送给服务器的数据必须为json格式。如下:

				Map map = new HashMap();
				map.put("key", "vaule");
                JSONObject jsonObject = new JSONObject(map);
                RequestBody requestBodyJson = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
                
                okhttp3.Request requestPostJson = new okhttp3.Request.Builder()
                        .url(baseUrl)
                        .post(requestBodyJson)
                        .build();

                OkHttpClient okHttpClientPostJson = new OkHttpClient();
                okHttpClientPostJson.newCall(requestPostJson).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                        String message = e != null ? e.getMessage() : "";
                        Log.e(TAG, "onFailure: "+message );
                    }

                    @Override
                    public void onResponse(Call call, okhttp3.Response response) throws IOException {

                        String body = response.body().string();
                        Log.e(TAG, "onResponse: body = " + body);
                    }
                });                

okgo框架 application/json 请求

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, createBodyJson(mModel));
        OkGo.<String>post(requestUrl).tag(this).upRequestBody(body).execute(new StringDialogCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                super.onSuccess(response);

                String body = response.body();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值