okhttp请求使用教程,多个header(请求头)get、post发送,发送post http请求消息体为json格式,get请求

okhttp请求使用教程,多个header请求头get、post发送,发送post http请求消息体为json格式,get请求

    • 引入pom依赖
    • 发送okhttp的utill工具类
    • 请求头实体

引入pom依赖

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

发送okhttp的utill工具类

package com.shus.dataapi.application.event;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.shus.dataapi.api.vo.ManagerResultStatusEnum;
import com.shus.dataapi.application.vo.RequestHeaderDO;
import com.shus.dataapi.infrastructure.util.ServiceException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class OkHttpUtil {
	
	//请求参数格式
    public static final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");

	//请求配置
    public final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(8000, TimeUnit.MILLISECONDS) 	
            .readTimeout(8000, TimeUnit.MILLISECONDS)
            .build();
			
	/**
     * 整理请求头信息
     * @param requestHeaderDOList 请求头
     * @return
     */
    public static Headers SetHeaders(List<RequestHeaderDO> requestHeaderDOList) {
        Headers headers = null;
        okhttp3.Headers.Builder headersbuilder = new okhttp3.Headers.Builder();
        if (CollectionUtils.isNotEmpty(requestHeaderDOList)) {
            requestHeaderDOList.forEach(requestHeaderDO -> {
                headersbuilder.add(requestHeaderDO.getKey(), requestHeaderDO.getValue());
            });
        }
        headers = headersbuilder.build();
        return headers;
    }


    /**
     * 发送post请求通过JSON参数
     *
     * @param reqUrl 请求url
     * @param param  请求参数
	 * @param requestHeaderDOList  请求头
     */
    public JsonObject sendPostByJsonAndHeader(String reqUrl, Object param, List<RequestHeaderDO> requestHeaderDOList) {
        JsonObject jsonObject = null;
        try {
            String paramStr = JSON.toJSONString(param);

            RequestBody requestBody = RequestBody.create(jsonType, paramStr);
            long startTime = System.currentTimeMillis();

            Headers headers = SetHeaders(requestHeaderDOList);

            Request.Builder builder = new Request.Builder().url(reqUrl).post(requestBody).headers(headers);
            String body = null;
            try (Response response = okHttpClient.newCall(builder.build()).execute()) {
                body = response.body().string();
                jsonObject = new Gson().fromJson(body, JsonObject.class);
            } catch (Exception e) {
                log.error("[OkHttpUtil]-[sendPostByJsonAndHeader]-[response:{},Exception:{}]", body, ExceptionUtils.getMessage(e));
                throw new ServiceException(ManagerResultStatusEnum.API_REQUEST_EXCEPTION.getStatus(), ManagerResultStatusEnum.API_REQUEST_EXCEPTION.getComment());
            } finally {
                long endTime = System.currentTimeMillis();
                log.info("OkHttpUtil:{} cost time:{}", reqUrl.substring(reqUrl.lastIndexOf("/") + 1),
                        (endTime - startTime));
            }
        } catch (Exception e) {
            log.error("[sendPostByJsonAndHeader:OkHttpUtil2]-[error:{}]", e);
        }
        return jsonObject;
    }

	/**
     * 发送get请求多个请求头
     * @param url   http请求地址
     * @param requestHeaderDOList  http请求头
     * @return
     */
    public JsonObject sendGetByHeader(String url, List<RequestHeaderDO> requestHeaderDOList) {
        // 设置HTTP请求参数
        JsonObject jsonObject = null;
        try {
            Headers setHeaders = SetHeaders(requestHeaderDOList);
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url).headers(setHeaders).build();

            String body = null;
            try (Response response = okHttpClient.newCall(request).execute()) {
                body = response.body().string();
                jsonObject = new Gson().fromJson(body, JsonObject.class);
            } catch (Exception e) {
                log.error("[OkHttpUtil]-[sendGetByHeader]-[response:{},Exception:{}]", body, ExceptionUtils.getMessage(e));
                throw new ServiceException(ManagerResultStatusEnum.API_REQUEST_EXCEPTION.getStatus(), ManagerResultStatusEnum.API_REQUEST_EXCEPTION.getComment());
            }
        } catch (Exception e) {
            log.error("[sendGetByHeader:OkHttpUtil2]-[error:{}]", e);
        }

        return jsonObject;
    }

	/**
     *	发送get请求
     * @param url
     * @return
     */
    public JsonObject sendGet(String url) {
        // 设置HTTP请求参数
        JsonObject jsonObject = null;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();

            String body = null;
            try (Response response = okHttpClient.newCall(request).execute()) {
                body = response.body().string();
                jsonObject = new Gson().fromJson(body, JsonObject.class);
            } catch (Exception e) {
                log.error("[OkHttpUtil]-[sendGet]-[response:{},Exception:{}]", body, ExceptionUtils.getMessage(e));
                throw new ServiceException(ManagerResultStatusEnum.API_REQUEST_EXCEPTION.getStatus(), ManagerResultStatusEnum.API_REQUEST_EXCEPTION.getComment());
            }
        } catch (Exception e) {
            log.error("[sendGet:OkHttpUtil2]-[error:{}]", e);
        }

        return jsonObject;
    }
	
	
	/**
     * 发送post请求通过JSON参数
     *
     * @param reqUrl 请求url
     * @param param  请求参数
     */
    public JsonObject sendPostByJson(String reqUrl, Object param) {
        JsonObject jsonObject = null;
        try {
            String paramStr = JSON.toJSONString(param);

            RequestBody requestBody = RequestBody.create(jsonType, paramStr);
            long startTime = System.currentTimeMillis();

            Request.Builder builder = new Request.Builder().url(reqUrl).post(requestBody);
            String body = null;
            try (Response response = okHttpClient.newCall(builder.build()).execute()) {
                body = response.body().string();
                jsonObject = new Gson().fromJson(body, JsonObject.class);
            } catch (Exception e) {
                log.error("[OkHttpUtil]-[sendPostByJsonAndHeader]-[response:{},Exception:{}]", body, ExceptionUtils.getMessage(e));
                throw new ServiceException(ManagerResultStatusEnum.API_REQUEST_EXCEPTION.getStatus(), ManagerResultStatusEnum.API_REQUEST_EXCEPTION.getComment());
            } finally {
                long endTime = System.currentTimeMillis();
                log.info("OkHttpUtil:{} cost time:{}", reqUrl.substring(reqUrl.lastIndexOf("/") + 1),
                        (endTime - startTime));
            }
        } catch (Exception e) {
            log.error("[sendPostByJsonAndHeader:OkHttpUtil2]-[error:{}]", e);
        }
        return jsonObject;
    }

}

请求头实体

package com.shus.dataapi.application.vo;

import lombok.Data;

@Data
public class RequestHeaderDO {

    private String key;

    private String value;
}

你可能感兴趣的:(http,post)