15
15
import org .apache .http .entity .ContentType ;
16
16
import org .apache .http .entity .mime .HttpMultipartMode ;
17
17
import org .apache .http .entity .mime .MultipartEntityBuilder ;
18
- import org .apache .http .entity .mime .content .InputStreamBody ;
19
18
import org .apache .http .impl .client .CloseableHttpClient ;
20
19
21
20
import java .io .*;
22
21
import java .util .Map ;
23
22
24
23
public class MaterialUploadRequestExecutor implements RequestExecutor <WxMpMaterialUploadResult , WxMpMaterial > {
25
24
25
+ @ Override
26
26
public WxMpMaterialUploadResult execute (CloseableHttpClient httpclient , HttpHost httpProxy , String uri , WxMpMaterial material ) throws WxErrorException , ClientProtocolException , IOException {
27
27
HttpPost httpPost = new HttpPost (uri );
28
28
if (httpProxy != null ) {
@@ -35,10 +35,10 @@ public WxMpMaterialUploadResult execute(CloseableHttpClient httpclient, HttpHost
35
35
if (file == null || !file .exists ()) {
36
36
throw new FileNotFoundException ();
37
37
}
38
- BufferedInputStream bufferedInputStream = new BufferedInputStream ( new FileInputStream ( file ));
38
+
39
39
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder .create ();
40
40
multipartEntityBuilder
41
- .addPart ("media" , new InputStreamBody ( bufferedInputStream , material . getName ()) )
41
+ .addBinaryBody ("media" , file )
42
42
.setMode (HttpMultipartMode .RFC6532 );
43
43
Map <String , String > form = material .getForm ();
44
44
if (material .getForm () != null ) {
@@ -48,13 +48,14 @@ public WxMpMaterialUploadResult execute(CloseableHttpClient httpclient, HttpHost
48
48
httpPost .setHeader ("Content-Type" , ContentType .MULTIPART_FORM_DATA .toString ());
49
49
}
50
50
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
+ }
58
59
}
59
60
}
60
61
0 commit comments