Java使用okhttp与WebAPI通信

1、引入依赖

<dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.10.0</version>
        </dependency>

2、GET请求

/**
     * 通过httpok 访问webapi get请求
     * @param url web api 路径
     * @return 响应的结果
     */
    public String getResultByGetUrl(String url)
    {

        Request getRequest = new Request.Builder()
                .url(url)
                .build();
        log.info("GETurl:{}",url);
        Response response = null;
        String reponseResult = null;
        try {
            response = client.newCall(getRequest).execute();
            reponseResult = Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            throw new RobotException(e,RobotExceptionConfstant.ROBOT_EXCEPTION_HTTPOK);
        }
        return reponseResult;
    }
View Code

3、POST请求

/**
     * 通过httpok 访问webapi post请求
     * @param json post请求的参数
     * @param url webApi的路径
     * @return 返回路径结果
     *
     */
    public String getResultByPostUrl(String json, String url)
    {

        RequestBody body = RequestBody.create(
                MediaType.parse("application/json"), json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        log.info("PostUrl:{},参数是:{}",url,json);
        Call call = client.newCall(request);
        Response response = null;
        String data = null;
        try {
            response = call.execute();
            data = Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            throw new RobotException(e, RobotExceptionConfstant.ROBOT_EXCEPTION_HTTPOK);
        }
        return data;
    }
View Code

 

posted @ 2023-01-27 19:09  Caesar_the_great  阅读(143)  评论(0编辑  收藏  举报