一次分析接口对接,需要上传文件,使用httpclient始终报错,使用postman调试,测通了。于是想到了postman的代码生成功能,可以将测通代码拿来调整一下使用。
其他的各种参数类型都可以先用postman测通,然后参考生成的代码,减少工作量。
生成的代码依赖是http3,由此封装出okhttp3的工具类,方便后续使用。
maven依赖
<!-- okhttp3-->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.3.0</version>
</dependency>
<!-- commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<!--GetByteEncode-->
<dependency>
<groupId>com.googlecode.juniversalchardet</groupId>
<artifactId>juniversalchardet</artifactId>
<version>1.0.3</version>
</dependency>
<!--GetByteEncode-->
<dependency>
<groupId>com.googlecode.juniversalchardet</groupId>
<artifactId>juniversalchardet</artifactId>
<version>1.0.3</version>
</dependency>
<!-- commons-lang -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
package com.wg.utils;
import okhttp3.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.RequestBuilder;
import org.elasticsearch.client.Requests;
import org.mozilla.universalchardet.UniversalDetector;
import javax.net.ssl.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class OkHttpUtil {
//单例构造
static class Singlton{
public static OkHttpClient client = new okhttp3.OkHttpClient.Builder()
.readTimeout(20, TimeUnit.SECONDS)//读取超时
.connectTimeout(60, TimeUnit.SECONDS)//连接超时
.writeTimeout(60, TimeUnit.SECONDS)//写入超时
支持HTTPS请求,跳过证书验证
.sslSocketFactory(createSSLSocketFactory())
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.build();
}
private static Map<String, String> defaultHeader = new HashMap<>();
static {
defaultHeader.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
// defaultHeader.put("Accept-Encoding", "gzip, deflate"); //okhttp不支持这个参数的解压缩
defaultHeader.put("accept-language", "zh-CN,zh;q=0.9,en;q=0.8");
defaultHeader.put("cache-control", "max-age=0");
defaultHeader.put("upgrade-insecure-requests", "1");
defaultHeader.put("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
defaultHeader.put("referer", "https://www.baidu.com");
}
/**
* 文件上传
* @param file
* @param url
* @param name
* @return
*/
public static String upload(File file,String url,String name){
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(60*5, TimeUnit.SECONDS)
.readTimeout(60*5, TimeUnit.SECONDS)
.build();
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart(name,file.getName(),
RequestBody.create(MediaType.parse("application/octet-stream"),
file))
.build();
Request request = new Request.Builder()
.url(url)
.method("POST", body)
.build();
return execute(request);
}
private static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
/**
* 生成安全套接字工厂,用于https请求的证书跳过
* @return
*/
public static SSLSocketFactory createSSLSocketFactory() {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
}
return ssfFactory;
}
/**
* 用于信任所有证书
*/
static class TrustAllCerts implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
public static String postJson(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = Singlton.client.newCall(request).execute();
return response.body().string();
}
public static String postJson(String url, String json,Map<String,String> headerMap) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.headers(getHeaders(headerMap))
.post(body)
.build();
Response response = Singlton.client.newCall(request).execute();
return response.body().string();
}
public static String postForm(String url, Map<String,String> forms) throws IOException {
FormBody.Builder formBuilder = new FormBody.Builder();
for (Map.Entry<String, String> entry : forms.entrySet()) {
formBuilder.add(entry.getKey(),entry.getValue());
//使用 addEncoded() 方法,添加已经被编码(utf-8)的参数的值 ,okhttp将不再对此参数的值进行默认编码
// formBuilder.addEncoded(entry.getKey(),encode(entry.getValue()));
}
FormBody body =formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
return execute(request);
}
private static String encode(String str){
try {
return URLEncoder.encode(str,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static String execute(Request request){
Response response=null;
try {
response = Singlton.client.newCall(request).execute();
if (response.isSuccessful()) {
byte[] bytes = response.body().bytes();
String encoding = getEncoding(bytes);
return new String(bytes, encoding);
}else {
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(response!=null){
response.close();
}
}
return null;
}
public static String execute(Request request,String charset){
Response response=null;
try {
response = Singlton.client.newCall(request).execute();
if (response.isSuccessful()) {
return new String(response.body().bytes(), charset);
}else {
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(response!=null){
response.close();
}
}
return null;
}
/**
* curl -XDELETE
* @param url
* @param reqbody
* @param map
* @return
*/
public static String doDelete(String url,String reqbody,Map<String,Object> map){
FormBody.Builder builder=addParamToBuilder(reqbody, map);
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.delete(body)
.build();
return execute(request);
}
public static String doGet(String url,Map<String,String> headerMap,String charset){
Headers mHeaders=getHeaders(headerMap);
Request request = new Request.Builder()
.get()
.url(url)
.headers(mHeaders)
.build();
return execute(request,charset);
}
/**
* 封装header
* @param headerMap
* @return
*/
public static Headers getHeaders(Map<String,String> headerMap){
Headers mHeaders=null;
if(headerMap==null){
mHeaders = Headers.of(defaultHeader);
}else {
mHeaders = Headers.of(headerMap);
}
return mHeaders;
}
/**
* curl -XPOST
* @param url
* @param reqbody
* @param map
* @return
*/
public static String doPost(String url,String reqbody,Map<String,Object> map){
FormBody.Builder builder=addParamToBuilder(reqbody, map);
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
return execute(request);
}
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
/**
* curl -XPOST 请求体带json
* @param url
* @param reqbody
* @return
*/
public static String doPost(String url,String reqbody){
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, reqbody))
.build();
return execute(request);
}
public static FormBody.Builder addParamToBuilder(String reqbody,Map<String,Object> map){
FormBody.Builder builder = new FormBody.Builder();
if(!StringUtils.isEmpty(reqbody)){
if(reqbody.startsWith("?")){
reqbody=reqbody.substring(1);
}
String[] params=reqbody.split("&");
for(int i=0;i<params.length;i++){
if(params[i].equals("")){
continue;
}
String [] kv=params[i].split("=");
builder.add(kv[0], kv[1]);
}
}
if(map!=null){
Iterator<Map.Entry<String,Object>> ite= map.entrySet().iterator();
for(;ite.hasNext();){
Map.Entry<String,Object> kv=ite.next();
builder.add(kv.getKey(), kv.getValue().toString());
}
}
return builder;
}
public static void downFile(String url,String dataDir,String fileName,boolean deleteOld){
File dataFile =new File( new File(dataDir)+File.separator+fileName);
if(!dataFile.getParentFile().exists()){
dataFile.mkdirs();
}else {
if(deleteOld){
dataFile.delete();
}
}
Request request = new Request.Builder()
.get()
.url(url)
.build();
Response response=null;
try {
response = Singlton.client.newCall(request).execute();
FileUtils.copyInputStreamToFile(response.body().byteStream(),dataFile);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(response!=null){
response.close();
}
}
}
/**
* 获取编码
* @param bytes
* @return
*/
public static String getEncoding(byte[] bytes) {
String defaultEncoding = "UTF-8";
UniversalDetector detector = new UniversalDetector(null);
detector.handleData(bytes, 0, bytes.length);
detector.dataEnd();
String encoding = detector.getDetectedCharset();
detector.reset();
System.out.println("字符编码是:"+ encoding);
if (encoding == null) {
encoding = defaultEncoding;
}
return encoding;
}
}