|
| 1 | +package cn.binarywang.wx.miniapp.executor; |
| 2 | + |
| 3 | +import cn.binarywang.wx.miniapp.bean.WxMaUploadAuthMaterialResult; |
| 4 | +import me.chanjar.weixin.common.enums.WxType; |
| 5 | +import me.chanjar.weixin.common.error.WxError; |
| 6 | +import me.chanjar.weixin.common.error.WxErrorException; |
| 7 | +import me.chanjar.weixin.common.util.http.RequestHttp; |
| 8 | +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; |
| 9 | +import org.apache.http.HttpEntity; |
| 10 | +import org.apache.http.HttpHost; |
| 11 | +import org.apache.http.client.config.RequestConfig; |
| 12 | +import org.apache.http.client.methods.CloseableHttpResponse; |
| 13 | +import org.apache.http.client.methods.HttpPost; |
| 14 | +import org.apache.http.entity.mime.HttpMultipartMode; |
| 15 | +import org.apache.http.entity.mime.MultipartEntityBuilder; |
| 16 | +import org.apache.http.impl.client.CloseableHttpClient; |
| 17 | + |
| 18 | +import java.io.File; |
| 19 | +import java.io.IOException; |
| 20 | + |
| 21 | +/** |
| 22 | + * @author penhuozhu |
| 23 | + * @since 2024/01/07 |
| 24 | + */ |
| 25 | +public class ApacheUploadAuthMaterialRequestExecutor extends UploadAuthMaterialRequestExecutor<CloseableHttpClient, HttpHost> { |
| 26 | + |
| 27 | + public ApacheUploadAuthMaterialRequestExecutor(RequestHttp requestHttp) { |
| 28 | + super(requestHttp); |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public WxMaUploadAuthMaterialResult execute(String uri, File file, WxType wxType) throws WxErrorException, IOException { |
| 33 | + HttpPost httpPost = new HttpPost(uri); |
| 34 | + if (requestHttp.getRequestHttpProxy() != null) { |
| 35 | + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); |
| 36 | + httpPost.setConfig(config); |
| 37 | + } |
| 38 | + if (file != null) { |
| 39 | + HttpEntity entity = MultipartEntityBuilder |
| 40 | + .create() |
| 41 | + .addBinaryBody("media", file) |
| 42 | + .setMode(HttpMultipartMode.RFC6532) |
| 43 | + .build(); |
| 44 | + httpPost.setEntity(entity); |
| 45 | + } |
| 46 | + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { |
| 47 | + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); |
| 48 | + WxError error = WxError.fromJson(responseContent, wxType); |
| 49 | + if (error.getErrorCode() != 0) { |
| 50 | + throw new WxErrorException(error); |
| 51 | + } |
| 52 | + return WxMaUploadAuthMaterialResult.fromJson(responseContent); |
| 53 | + } finally { |
| 54 | + httpPost.releaseConnection(); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments