前言:每次看到原生的http请求,不只是看起来难受,使用起来也难受,因为刚毕业时开发了半年的android,okhttp+rxjava使用也是得心应手(后端比安卓舒服的一点是,直接请求即可,不用考虑网络请求会阻塞UI线程这种东西),完全转后端后,偶尔也还是会用到http请求的,但是原生的确实难用,所以每次都是使用okhttp解决的,最近接触了一下微信支付,示例给的demo还是原生的,也是看的难受,所以下面简单的封装了一下基于okhttp微信支付的方法。
下面的示例是企业支付到用户的方法,其他的大同小异,代码如下:
/**
* 微信企业支付到用户操作
*
* @param requestData 请求的数据
* @param keystorePath 签名文件路径
* @return
*/
public static Map wxTransfers(String url, Map requestData, String mchid, String keystorePath) throws Exception {
if (requestData == null || requestData.isEmpty() || StringUtils.isEmpty(keystorePath)) {
throw new Exception("requestData or keyStorePath can't be null or empty");
}
String requestParam = WXPayUtil.mapToXml(requestData);
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream inputStream = new FileInputStream(new File(keystorePath));
try {
keyStore.load(inputStream, mchid.toCharArray());
} finally {
inputStream.close();
}
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(keyStore, mchid.toCharArray())
.build();
if (sslContext == null) {
Map resultMap = new HashMap<>();
resultMap.put("message", "获取证书文件失败");
return resultMap;
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory())
.addInterceptor(chain -> {
Request request = chain.request()
.newBuilder()
.addHeader("Content-Type", "text/plain; charset=utf-8")
.addHeader("content", "text/plain; charset=utf-8")
.build();
return chain.proceed(request);
})
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();
RequestBody requestBody = RequestBody.create(requestParam, OkHttpDataType.PLAIN_TYPE);
Request request = new Request.Builder()
.post(requestBody)
.url(url)
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return WXPayUtil.xmlToMap(response.body().string());
} else {
Map resultMap = new HashMap<>();
resultMap.put("message", response.message());
return resultMap;
}
}
其中requestData是请求的数据,只要按照微信API中的参数,塞进map传递进来即可,不需要去排序什么的了,顺序随意,方法里的WXPayUtil.mapToXml是那的微信提供的demo中的方法,自行下载demo就能找到的。
上面的方法中,还有个OkHttpDataType为OkHttp中的MediaType,完整类型如下所示:
/**
* HTML格式
*
* @return
*/
public static final MediaType HTML_TYPE = MediaType.parse("text/html;charset=utf-8");
/**
* 纯文本格式
*
* @return
*/
public static final MediaType PLAIN_TYPE = MediaType.parse("text/plain;charset=utf-8");
/**
* XML格式
*
* @return
*/
public static final MediaType XML_TYPE = MediaType.parse("text/xml;charset=utf-8");
/**
* gif图片格式
*
* @return
*/
public static final MediaType GIF_TYPE = MediaType.parse("image/gif");
/**
* jpg图片格式
*
* @return
*/
public static final MediaType JPG_TYPE = MediaType.parse("image/jpeg");
/**
* png图片格式
*
* @return
*/
public static MediaType PNG_TYPE = MediaType.parse("image/png");
/**
* XHTML格式
*
* @return
*/
public static final MediaType XHTML_TYPE = MediaType.parse("application/xhtml+xml;charset=utf-8");
/**
* XML数据格式
*
* @return
*/
public static final MediaType XML_DATA_TYPE = MediaType.parse("application/xml;charset=utf-8");
/**
* Atom XML聚合格式
*
* @return
*/
public static final MediaType ATOM_XML_TYPE = MediaType.parse("application/atom+xml;charset=utf-8");
/**
* JSON数据格式
*
* @return
*/
public static final MediaType JSON_TYPE = MediaType.parse("application/json;charset=utf-8");
/**
* pdf格式
*
* @return
*/
public static final MediaType PDF_TYPE = MediaType.parse("application/pdf");
/**
* Word文档格式
*
* @return
*/
public static final MediaType WORD_TYPE = MediaType.parse("application/msword");
/**
* 二进制流数据(如常见的文件下载)
*
* @return
*/
public static final MediaType STREAM_TYPE = MediaType.parse("application/octet-stream");
/**
*
下面是一些常用的基于OkHttp封装的简单请求,更多的使用方式,请查阅OkHttp官当文档,不过目前最新的OkHttp已经是基于kotlin开发了,看起来不错,个人表示很喜欢kotlin,也把kotlin用在项目上了,简单封装的代码如下:
/**
* get请求
*
* @param url
* @return
* @throws Exception
*/
public static String doGet(String url) throws Exception {
if (StringUtils.isEmpty(url)) {
throw new Exception("url can't be null or empty");
}
if (!url.startsWith("http")) {
throw new IllegalArgumentException("requst url illegal");
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.get()
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return response.message();
}
}
/**
* get请求并返回数据
*
* @param url 请求链接
* @param connectionTimeOut 请求时间
* @return
*/
public static String doGet(String url, int connectionTimeOut) throws Exception {
if (StringUtils.isEmpty(url)) {
throw new Exception("url can't be null or empty");
}
if (!url.startsWith("http")) {
throw new IllegalArgumentException("requst url illegal");
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.get()
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return response.message();
}
}
/**
* 带请求头的get请求
*
* @param url
* @param headers
* @return
* @throws Exception
*/
public static String doGet(String url, Map headers) throws Exception {
if (StringUtils.isEmpty(url)) {
throw new Exception("url can't be null or empty");
}
if (!url.startsWith("http")) {
throw new IllegalArgumentException("requst url illegal");
}
if (headers == null || headers.isEmpty()) {
throw new Exception("header can't be null or empty");
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(chain -> chain.proceed(chain.request().newBuilder().headers(Headers.of(headers)).build()))
.connectTimeout(10, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.get()
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return response.message();
}
}
/**
* 带请求头的get请求
*
* @param url 请求链接
* @param connectionTimeOut 请求超时限制(单位为秒)
* @param headers 请求头
* @return
* @throws Exception
*/
public static String doGet(String url, int connectionTimeOut, Map headers) throws Exception {
if (StringUtils.isEmpty(url)) {
throw new Exception("url can't be null or empty");
}
if (!url.startsWith("http")) {
throw new IllegalArgumentException("requst url illegal");
}
if (headers == null || headers.isEmpty()) {
throw new Exception("header can't be null or empty");
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(chain -> chain.proceed(chain.request().newBuilder().headers(Headers.of(headers)).build()))
.connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.get()
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return response.message();
}
}
/**
* post请求
*
* @param url
* @param data
* @return
* @throws Exception
*/
public static String doPost(String url, String data) throws Exception {
if (StringUtils.isEmpty(url)) {
throw new Exception("url can't be null or empty");
}
if (!url.startsWith("http")) {
throw new IllegalArgumentException("requst url illegal");
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.callTimeout(10, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(data, OkHttpDataType.JSON_TYPE))
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return response.message();
}
}
/**
* post请求
*
* @param url 请求链接
* @param connectionTimeOut 请求超时限制(单位:秒)
* @param data
* @return
* @throws Exception
*/
public static String doPost(String url, int connectionTimeOut, String data) throws Exception {
if (StringUtils.isEmpty(url)) {
throw new Exception("url can't be null or empty");
}
if (!url.startsWith("http")) {
throw new IllegalArgumentException("requst url illegal");
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
.callTimeout(connectionTimeOut, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(data, OkHttpDataType.JSON_TYPE))
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return response.message();
}
}
/**
* post请求数据
*
* @param url
* @param data
* @param connectionTimeOut
* @param headers
* @return
*/
public static String doPost(String url, String data, int connectionTimeOut, final Map headers) throws Exception {
if (StringUtils.isEmpty(url)) {
throw new Exception("url can't be null or empty");
}
if (!url.startsWith("http")) {
throw new IllegalArgumentException("requst url illegal");
}
if (headers == null || headers.isEmpty()) {
throw new Exception("header can't be null or empty");
}
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(chain -> chain.proceed(chain.request().newBuilder().headers(Headers.of(headers)).build()))
.connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
.build();
RequestBody requestBody = RequestBody.create(data, OkHttpDataType.JSON_TYPE);
Request request = new Request.Builder()
.post(requestBody)
.url(url)
.build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return null;
}
}
/**
* post请求数据
*
* @param url
* @param data
* @param connectionTimeOut
* @param headers
* @return
*/
public static String doPost(String url, String data, int connectionTimeOut, MediaType type, final Map headers) throws Exception {
if (StringUtils.isEmpty(url)) {
throw new Exception("url can't be null or empty");
}
if (!url.startsWith("http")) {
throw new IllegalArgumentException("requst url illegal");
}
if (headers == null || headers.isEmpty()) {
throw new Exception("header can't be null or empty");
}
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(chain -> chain.proceed(chain.request().newBuilder().headers(Headers.of(headers)).build()))
.connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
.build();
RequestBody requestBody = RequestBody.create(data, type);
Request request = new Request.Builder()
.post(requestBody)
.url(url)
.build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return null;
}
}
/**
* post请求数据
*
* @param url
* @param data
* @param connectionTimeOut
* @param headerMap
* @return
*/
public static String doPostWithAuthorization(String url, String data, final String credential, int connectionTimeOut, final Map headerMap) throws IOException {
if (url == null || data == null) {
throw new NullPointerException("url or data can't be null");
}
OkHttpClient httpClient = new OkHttpClient.Builder()
.authenticator((route, response) -> response.request().newBuilder()
.header("Authorization", credential)
.build())
.addInterceptor(chain -> {
Request request = null;
if (headerMap == null) {
request = chain.request()
.newBuilder()
.addHeader("Content-Type", "application/json;utf-8")
.build();
} else {
Headers headers = Headers.of(headerMap);
request = chain.request().newBuilder().headers(headers).build();
}
return chain.proceed(request);
})
.connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
.build();
RequestBody requestBody = RequestBody.create(data, OkHttpDataType.JSON_TYPE);
Request request = new Request.Builder()
.post(requestBody)
.url(url)
.build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return null;
}
}
/**
* post提交表单数据
*
* @param url
* @param data
* @param connectionTimeOut
* @param headerMap
* @return
*/
public static String doPostWithForm(String url, HashMap data, int connectionTimeOut, final Map headerMap) throws IOException {
if (url == null || data == null) {
throw new NullPointerException("url or data can't be null");
}
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(chain -> {
Request request = null;
if (headerMap == null) {
request = chain.request()
.newBuilder()
.addHeader("Content-Type", "application/json;utf-8")
.build();
} else {
Headers headers = Headers.of(headerMap);
request = chain.request().newBuilder().headers(headers).build();
}
return chain.proceed(request);
})
.connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
.build();
// 构建请求数据表单
FormBody.Builder builder = new FormBody.Builder();
for (String key : data.keySet()) {
builder.add(key, String.valueOf(data.get(key)));
}
Request request = new Request.Builder()
.post(builder.build())
.url(url)
.build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return null;
}
}
好了,要说的就到这把,希望能帮到需要帮的人。