public class OkHttpUtils {
private static OkHttpClient.Builder BUILDER = null;
private static final String DEFAULT_CHARSET = "utf-8";
static {
BUILDER = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS);
}
private static SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new MyX509TrustManager()}, new SecureRandom());
return sslContext.getSocketFactory();
}
public static void doGet(String url, Map<String, Object> params, Map<String, String> headers, boolean https) {
Request.Builder builder = new Request.Builder();
//构造请求参数
if (params != null && !params.isEmpty()) {
StringBuilder sb = new StringBuilder(url);
if (!url.contains("?")) {
sb.append("?");
}
params.forEach((k, v) -> sb.append(k).append("=").append(v).append("&"));
sb.setCharAt(sb.length() - 1, ' ');
url = sb.toString().trim();
}
//构造请求头部
if (headers != null && !headers.isEmpty()) {
headers.forEach((k, v) -> builder.addHeader(k, v));
}
Request request = builder.get().url(url).build();
try {
if (https){
BUILDER.sslSocketFactory(getSSLSocketFactory(),new MyX509TrustManager())
// .hostnameVerifier((s, sslSession)-> true)
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
}
Response response = BUILDER.build().newCall(request).execute();
if (!response.isSuccessful()) {
System.out.println("请求失败");
} else {
InputStream in = response.body().byteStream();
byte[] bytes = streamConvertToByte(in);
String str = new String(bytes);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
public static void httpPost(String url, List<FileTerm> files, Map<String, String> params, Map<String, String> headers) {
Request.Builder builder = new Request.Builder();
//构造请求头部
if (!headers.isEmpty() && headers.size() > 0) {
headers.forEach(builder::addHeader);
}
// MediaType mediaType = MediaType.parse("multipart/form-data; charset="+ DEFAULT_CHARSET);
MultipartBody.Builder mltBuilder = new MultipartBody
.Builder()
.setType(MultipartBody.FORM);
//构造文本请求参数
if (params != null && !params.isEmpty()) {
params.forEach(mltBuilder::addFormDataPart);
}
//构造文件请求
if (files != null && !files.isEmpty()) {
files.forEach((file) -> {
System.out.println(MediaType.parse(file.getMimeType()));
RequestBody requestBody = RequestBody.create(MediaType.parse(file.getMimeType()), file.getFile());
mltBuilder.addFormDataPart(file.getFileName(), file.getFile().getName(), requestBody);
});
}
Request request = builder.url(url)
.post(mltBuilder.build())
.build();
try {
Response response = BUILDER.build().newCall(request).execute();
if (!response.isSuccessful()) {
System.out.println("请求失败");
} else {
InputStream in = response.body().byteStream();
byte[] bytes = streamConvertToByte(in);
String str = new String(bytes);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] streamConvertToByte(InputStream input) throws IOException {
byte[] bytes = new byte[1024];
byte[] result = null;
int read;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
while ((read = input.read(bytes, 0, bytes.length)) != -1) {
baos.write(bytes, 0, read);
}
result = baos.toByteArray();
baos.close();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (baos != null) {
baos.close();
}
if (input != null) {
input.close();
}
}
return result;
}
}
OkHttp的使用
最新推荐文章于 2023-04-11 19:56:43 发布