cn.takujo.common_api.util.HttpUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of common-api Show documentation
Show all versions of common-api Show documentation
takujoframework common-api
package cn.takujo.common_api.util;
import java.io.IOException;
import cn.takujo.common_api.exception.HttpException;
import okhttp3.FormBody.Builder;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public final class HttpUtil {
private static OkHttpClient ClIENT = new OkHttpClient();
public static final MediaType JSON = MediaType.get("application/json;charset=utf-8");
public static String get(String url) throws HttpException {
Request request = new Request.Builder().url(url).build();
try (Response response = ClIENT.newCall(request).execute()) {
return response.body().string();
} catch (IOException e) {
throw new HttpException("http01", "get请求失败");
}
}
public static String post(String url, String json) throws HttpException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).post(body).build();
try (Response response = ClIENT.newCall(request).execute()) {
return response.body().string();
} catch (IOException e) {
throw new HttpException("http02", "post请求失败");
}
}
/**
* 通过表单方式提交
*
* @param url
* 请求地址
* @param parm
* FormBody.Builder,通过add方法设置传参
* @return 响应体字符串
* @throws HttpException
* http请求异常
*/
public static String postByForm(String url, Builder parm) throws HttpException {
RequestBody body = parm.build();
Request request = new Request.Builder().url(url).post(body).build();
try (Response response = ClIENT.newCall(request).execute()) {
return response.body().string();
} catch (IOException e) {
throw new HttpException("http03", "postByForm请求失败");
}
}
}