okHttp工具类


import com.google.gson.Gson;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 *         <dependency>
 *             <groupId>com.squareup.okhttp3</groupId>
 *             <artifactId>okhttp</artifactId>
 *         </dependency>
 *         <dependency>
 *             <groupId>com.google.code.gson</groupId>
 *             <artifactId>gson</artifactId>
 *         </dependency>
 */

/**
 * okhttp工具类
 */
public class HttpUtils {

    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    public static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    final OkHttpClient client
        = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(20, TimeUnit.SECONDS)
        .build();

    public String postJson(String url, HashMap<String, String> map) throws IOException {


        if (map == null || StringUtils.isEmpty(url)) {
            throw new RuntimeException("url或请求参数不能为空");
        }

        Gson gson = new Gson();
        String json = gson.toJson(map);
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();

        try (Response response = client.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new RuntimeException("响应体为空");
            }
            return responseBody.string();
        } catch (Exception e) {
            logger.error(e.toString());
            return "";
        }
    }

    /**
     * 需要使用序列化工具将对象序列化成字符串:如gson
     *
     * @param url
     * @param json
     * @return
     */
    public String postJson(String url, String json) {

        if (StringUtils.isEmpty(json) || StringUtils.isEmpty(url)) {
            throw new RuntimeException("url或请求参数不能为空");
        }

        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();

        try (Response response = client.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new RuntimeException("响应体为空");
            }
            return responseBody.string();
        } catch (Exception e) {
            logger.error(e.toString());
            return "";
        }
    }

    /** 
     * @param url
     * @param queryParamMap
     * @return
     */
    public String get(String url, HashMap<String, String> queryParamMap) throws IOException {

        if (StringUtils.isEmpty(url)) {
            throw new RuntimeException("url或请求参数不能为空");
        }

        HttpUrl.Builder builder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        if (queryParamMap != null && queryParamMap.size() != 0) {
            queryParamMap.forEach(builder::addQueryParameter);
        }
        url = builder.build().toString();

        Request request = new Request.Builder()
            .url(url)
            .build();
        try (Response response = client.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new RuntimeException("响应体为空");
            }
            return responseBody.string();
        } catch (Exception e) {
            logger.error(e.toString());
            return "";
        }
    }

    public static void main(String[] args) throws IOException {

        HashMap<String, String> map = new HashMap<>(8);
        map.put("name", "b");
        map.put("schoolNo", "1212b");
        //
        // HttpUtils httpUtils = new HttpUtils();
        // String response = httpUtils.postJson("http://localhost:8080/repeat/createOrder", map);
        // System.out.println(response);
        //
        // System.out.println("==============");
        //
        // DemoData demoData = new DemoData();
        // demoData.setName("zs");
        // demoData.setSchoolNo("李集小学");
        // String json = new Gson().toJson(demoData);
        //
        // HttpUtils httpUtils2 = new HttpUtils();
        // String response2 = httpUtils2.postJson("http://localhost:8080/repeat/createOrder", json);
        // System.out.println(response2);

        // HttpUtils httpUtils3 = new HttpUtils();
        // String response3 = httpUtils3.get("http://localhost:8080/repeat/token", map);
        // System.out.println(response3);
    }
}

posted @ 2022-11-11 23:42  永无八哥  阅读(777)  评论(0编辑  收藏  举报