OkHTTP发送POST请求传送JSON数据

导入依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.14.9</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
    </dependencies>

编写一个接口

    @RequestMapping("/Json")
    @ResponseBody
    public JSONObject Json(@RequestBody JSONObject map) {
        System.out.println(map);
        map.put("success", true);
        map.put("msg", UUID.randomUUID().toString());
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("token", "asdascfr22rwf");
        map.put("response", stringObjectHashMap);
        return map;
    }

编写OkHTTP的测试类发送请求这个接口

package com.example.demo.demos.web;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class HttpClentTest {

    private final static String httpHeaderMediaType = "application/json;charset=utf-8";

    private final static String httpHeaderContentType = "Content-Type";

    private final static Logger logger = LoggerFactory.getLogger(HttpClentTest.class);

    /**
     * 设置默认30秒Http调用超时
     */
    private final static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .callTimeout(30, TimeUnit.SECONDS)
            .build();
    public static void main(String[] args) {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("appKey", UUID.randomUUID().toString());
        jsonBody.put("appSecret", UUID.randomUUID().toString());
        //  构建Request对象
        RequestBody requestBody = RequestBody.create(MediaType.parse(httpHeaderMediaType), jsonBody.toJSONString());
        Request request = new Request.Builder()
                .addHeader(httpHeaderContentType, httpHeaderMediaType)
                .addHeader("Accept", httpHeaderMediaType)
                .post(requestBody)
                .url("http://localhost:8282/Json")
                .build();
        Response signRsp = null;
        try {
            signRsp = client.newCall(request).execute();
            if (signRsp.isSuccessful()) {
                String body = signRsp.body().string();
                JSONObject respBody = JSONObject.parseObject(body);
                if (respBody.getBoolean("success")) {
                    System.out.println("===================================Token===================================");
                    System.out.println(respBody.getJSONObject("response").getString("token"));
                } else {
                    logger.error("Http连接OpenapiAPi地址:openapiLoginUrl  失败,MSG= {}", respBody.getString("msg"));
                }
            }
        } catch (IOException e) {
            logger.error("Http连接OpenapiAPi地址:openapiLoginUrl  失败", e);
        }
    }
}

成功测试结果

===================================Token===================================
asdascfr22rwf

posted on 2024-01-23 14:16  白嫖老郭  阅读(539)  评论(0编辑  收藏  举报

导航