|
| 1 | +package me.chanjar.weixin.mp.util.requestexecuter.ocr; |
| 2 | + |
| 3 | +import me.chanjar.weixin.common.error.WxError; |
| 4 | +import me.chanjar.weixin.common.error.WxErrorException; |
| 5 | +import me.chanjar.weixin.common.util.http.RequestHttp; |
| 6 | +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; |
| 7 | +import org.apache.http.HttpEntity; |
| 8 | +import org.apache.http.HttpHost; |
| 9 | +import org.apache.http.client.config.RequestConfig; |
| 10 | +import org.apache.http.client.methods.CloseableHttpResponse; |
| 11 | +import org.apache.http.client.methods.HttpPost; |
| 12 | +import org.apache.http.entity.mime.HttpMultipartMode; |
| 13 | +import org.apache.http.entity.mime.MultipartEntityBuilder; |
| 14 | +import org.apache.http.impl.client.CloseableHttpClient; |
| 15 | + |
| 16 | +import java.io.File; |
| 17 | +import java.io.IOException; |
| 18 | + |
| 19 | +/** |
| 20 | + * @author : zhayueran |
| 21 | + * @Date: 2019/6/27 14:06 |
| 22 | + * @Description: |
| 23 | + */ |
| 24 | +public class OcrDiscernApacheHttpRequestExecutor extends OcrDiscernRequestExecutor<CloseableHttpClient, HttpHost> { |
| 25 | + |
| 26 | + |
| 27 | + public OcrDiscernApacheHttpRequestExecutor(RequestHttp requestHttp) { |
| 28 | + super(requestHttp); |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public String execute(String uri, File file) 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("file", 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); |
| 49 | + if (error.getErrorCode() != 0) { |
| 50 | + throw new WxErrorException(error); |
| 51 | + } |
| 52 | + return responseContent; |
| 53 | + } finally { |
| 54 | + httpPost.releaseConnection(); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments