1+ package me .chanjar .weixin .mp .util .http ;
2+
3+ import me .chanjar .weixin .common .bean .result .WxError ;
4+ import me .chanjar .weixin .common .exception .WxErrorException ;
5+ import me .chanjar .weixin .common .util .http .RequestExecutor ;
6+ import me .chanjar .weixin .common .util .http .Utf8ResponseHandler ;
7+ import me .chanjar .weixin .mp .bean .result .WxMediaImgUploadResult ;
8+ import org .apache .http .HttpEntity ;
9+ import org .apache .http .HttpHost ;
10+ import org .apache .http .client .ClientProtocolException ;
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 .ContentType ;
15+ import org .apache .http .entity .mime .HttpMultipartMode ;
16+ import org .apache .http .entity .mime .MultipartEntityBuilder ;
17+ import org .apache .http .impl .client .CloseableHttpClient ;
18+
19+ import java .io .File ;
20+ import java .io .IOException ;
21+
22+ /**
23+ * @author miller
24+ */
25+ public class MediaImgUploadRequestExecutor implements RequestExecutor <WxMediaImgUploadResult , File > {
26+ @ Override
27+ public WxMediaImgUploadResult execute (CloseableHttpClient httpclient , HttpHost httpProxy , String uri , File data ) throws WxErrorException , ClientProtocolException , IOException {
28+ HttpPost httpPost = new HttpPost (uri );
29+ if (httpProxy != null ) {
30+ RequestConfig config = RequestConfig .custom ().setProxy (httpProxy ).build ();
31+ httpPost .setConfig (config );
32+ }
33+ if (data != null ) {
34+ HttpEntity entity = MultipartEntityBuilder
35+ .create ()
36+ .addBinaryBody ("media" , data )
37+ .setMode (HttpMultipartMode .RFC6532 )
38+ .build ();
39+ httpPost .setEntity (entity );
40+ httpPost .setHeader ("Content-Type" , ContentType .MULTIPART_FORM_DATA .toString ());
41+ }
42+ try (CloseableHttpResponse response = httpclient .execute (httpPost )) {
43+ String responseContent = Utf8ResponseHandler .INSTANCE .handleResponse (response );
44+ WxError error = WxError .fromJson (responseContent );
45+ if (error .getErrorCode () != 0 ) {
46+ throw new WxErrorException (error );
47+ }
48+ return WxMediaImgUploadResult .fromJson (responseContent );
49+ }
50+ }
51+ }
0 commit comments