OKHttp3带参数发送get和post请求工具类

时间:2024-11-13 19:41:19

 需要引入依赖

<dependency>
    <groupId>.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.3.1</version>
</dependency>
import ;
import ;
import ;

import okhttp3.*;

public class HttpUtil {
	private HttpUtil() {
	}

	/**
	 * 发送get请求
	 *
	 * @param url    地址
	 * @param params 参数
	 * @return 请求结果
	 */
	public static String get(String url, Map<String, String> params) {
		return request("get", url, params);
	}

	/**
	 * 发送post请求
	 *
	 * @param url    地址
	 * @param params 参数
	 * @return 请求结果
	 */
	public static String post(String url, Map<String, String> params) {
		return request("post", url, params);
	}

	/**
	 * 发送http请求
	 *
	 * @param method 请求方法
	 * @param url    地址
	 * @param params 参数
	 * @return 请求结果
	 */
	public static String request(String method, String url, Map<String, String> params) {

		if (method == null) {
			throw new RuntimeException("请求方法不能为空");
		}

		if (url == null) {
			throw new RuntimeException("url不能为空");
		}

		 httpBuilder = (url).newBuilder();

		if (params != null) {
			for (<String, String> param : ()) {
				((), ());
			}
		}

		Request request = new ()
				.url(())
				.method(method, new ().build())
				.build();

		try {
			OkHttpClient client = new ()
					.readTimeout(20, )
					.build();
			Response response = (request).execute();
			return ().string();
		} catch (IOException e) {
			return null;
		}
	}

	/**
	 * 发送post请求(json格式)
	 *
	 * @param url  url
	 * @param json json字符串
	 * @return 请求结果
	 */
	public static String postJson(String url, String json) {

		Request request = new ()
				.url(url)
				.post((json, ("application/json")))
				.build();

		try {
			OkHttpClient client = new OkHttpClient();
			Response response = (request).execute();
			return ().string();
		} catch (IOException e) {
			return null;
		}
	}
}