1515import org .apache .http .entity .ContentType ;
1616import org .apache .http .entity .mime .HttpMultipartMode ;
1717import org .apache .http .entity .mime .MultipartEntityBuilder ;
18- import org .apache .http .entity .mime .content .InputStreamBody ;
1918import org .apache .http .impl .client .CloseableHttpClient ;
2019
2120import java .io .*;
2221import java .util .Map ;
2322
2423public class MaterialUploadRequestExecutor implements RequestExecutor <WxMpMaterialUploadResult , WxMpMaterial > {
2524
25+ @ Override
2626 public WxMpMaterialUploadResult execute (CloseableHttpClient httpclient , HttpHost httpProxy , String uri , WxMpMaterial material ) throws WxErrorException , ClientProtocolException , IOException {
2727 HttpPost httpPost = new HttpPost (uri );
2828 if (httpProxy != null ) {
@@ -35,10 +35,10 @@ public WxMpMaterialUploadResult execute(CloseableHttpClient httpclient, HttpHost
3535 if (file == null || !file .exists ()) {
3636 throw new FileNotFoundException ();
3737 }
38- BufferedInputStream bufferedInputStream = new BufferedInputStream ( new FileInputStream ( file ));
38+
3939 MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder .create ();
4040 multipartEntityBuilder
41- .addPart ("media" , new InputStreamBody ( bufferedInputStream , material . getName ()) )
41+ .addBinaryBody ("media" , file )
4242 .setMode (HttpMultipartMode .RFC6532 );
4343 Map <String , String > form = material .getForm ();
4444 if (material .getForm () != null ) {
@@ -48,13 +48,14 @@ public WxMpMaterialUploadResult execute(CloseableHttpClient httpclient, HttpHost
4848 httpPost .setHeader ("Content-Type" , ContentType .MULTIPART_FORM_DATA .toString ());
4949 }
5050
51- CloseableHttpResponse response = httpclient .execute (httpPost );
52- String responseContent = Utf8ResponseHandler .INSTANCE .handleResponse (response );
53- WxError error = WxError .fromJson (responseContent );
54- if (error .getErrorCode () != 0 ) {
55- throw new WxErrorException (error );
56- } else {
57- return WxMpMaterialUploadResult .fromJson (responseContent );
51+ try (CloseableHttpResponse response = httpclient .execute (httpPost )) {
52+ String responseContent = Utf8ResponseHandler .INSTANCE .handleResponse (response );
53+ WxError error = WxError .fromJson (responseContent );
54+ if (error .getErrorCode () != 0 ) {
55+ throw new WxErrorException (error );
56+ } else {
57+ return WxMpMaterialUploadResult .fromJson (responseContent );
58+ }
5859 }
5960 }
6061
0 commit comments