Search in sources :

Example 11 with WxErrorException

use of me.chanjar.weixin.common.exception.WxErrorException in project weixin-java-tools by chanjarster.

the class QrCodeRequestExecutor method execute.

@Override
public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, WxMpQrCodeTicket ticket) throws WxErrorException, ClientProtocolException, IOException {
    if (ticket != null) {
        if (uri.indexOf('?') == -1) {
            uri += '?';
        }
        uri += uri.endsWith("?") ? "ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8") : "&ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8");
    }
    HttpGet httpGet = new HttpGet(uri);
    if (httpProxy != null) {
        RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
        httpGet.setConfig(config);
    }
    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        Header[] contentTypeHeader = response.getHeaders("Content-Type");
        if (contentTypeHeader != null && contentTypeHeader.length > 0) {
            // 出错
            if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) {
                String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
                throw new WxErrorException(WxError.fromJson(responseContent));
            }
        }
        InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);
        File localFile = FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg");
        return localFile;
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) Header(org.apache.http.Header) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) File(java.io.File) WxErrorException(me.chanjar.weixin.common.exception.WxErrorException)

Example 12 with WxErrorException

use of me.chanjar.weixin.common.exception.WxErrorException in project weixin-java-tools by chanjarster.

the class WxMpServiceImpl method sendRedpack.

@Override
public WxRedpackResult sendRedpack(Map<String, String> parameters) throws WxErrorException {
    String nonce_str = System.currentTimeMillis() + "";
    SortedMap<String, String> packageParams = new TreeMap<String, String>(parameters);
    packageParams.put("wxappid", wxMpConfigStorage.getAppId());
    packageParams.put("mch_id", wxMpConfigStorage.getPartnerId());
    packageParams.put("nonce_str", nonce_str);
    String sign = WxCryptUtil.createSign(packageParams, wxMpConfigStorage.getPartnerKey());
    packageParams.put("sign", sign);
    StringBuilder request = new StringBuilder("<xml>");
    for (Entry<String, String> para : packageParams.entrySet()) {
        request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey()));
    }
    request.append("</xml>");
    HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack");
    if (httpProxy != null) {
        RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
        httpPost.setConfig(config);
    }
    StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8);
    httpPost.setEntity(entity);
    try {
        CloseableHttpResponse response = getHttpclient().execute(httpPost);
        String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
        XStream xstream = XStreamInitializer.getInstance();
        xstream.processAnnotations(WxRedpackResult.class);
        WxRedpackResult wxMpRedpackResult = (WxRedpackResult) xstream.fromXML(responseContent);
        return wxMpRedpackResult;
    } catch (IOException e) {
        log.error(MessageFormatter.format("The exception was happened when sending redpack '{}'.", request.toString()).getMessage(), e);
        WxError error = new WxError();
        error.setErrorCode(-1);
        throw new WxErrorException(error);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) WxError(me.chanjar.weixin.common.bean.result.WxError) XStream(com.thoughtworks.xstream.XStream) IOException(java.io.IOException) TreeMap(java.util.TreeMap) WxErrorException(me.chanjar.weixin.common.exception.WxErrorException) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) WxRedpackResult(me.chanjar.weixin.mp.bean.result.WxRedpackResult)

Example 13 with WxErrorException

use of me.chanjar.weixin.common.exception.WxErrorException in project weixin-java-tools by chanjarster.

the class WxCpMessageRouterRule method service.

/**
   * 处理微信推送过来的消息
   *
   * @param wxMessage
   * @return true 代表继续执行别的router,false 代表停止执行别的router
   */
protected WxCpXmlOutMessage service(WxCpXmlMessage wxMessage, WxCpService wxCpService, WxSessionManager sessionManager, WxErrorExceptionHandler exceptionHandler) {
    try {
        Map<String, Object> context = new HashMap<String, Object>();
        // 如果拦截器不通过
        for (WxCpMessageInterceptor interceptor : this.interceptors) {
            if (!interceptor.intercept(wxMessage, context, wxCpService, sessionManager)) {
                return null;
            }
        }
        // 交给handler处理
        WxCpXmlOutMessage res = null;
        for (WxCpMessageHandler handler : this.handlers) {
            // 返回最后handler的结果
            res = handler.handle(wxMessage, context, wxCpService, sessionManager);
        }
        return res;
    } catch (WxErrorException e) {
        exceptionHandler.handle(e);
    }
    return null;
}
Also used : HashMap(java.util.HashMap) WxCpXmlOutMessage(me.chanjar.weixin.cp.bean.WxCpXmlOutMessage) WxErrorException(me.chanjar.weixin.common.exception.WxErrorException)

Example 14 with WxErrorException

use of me.chanjar.weixin.common.exception.WxErrorException in project weixin-java-tools by chanjarster.

the class MediaDownloadRequestExecutor method execute.

@Override
public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, ClientProtocolException, IOException {
    if (queryParam != null) {
        if (uri.indexOf('?') == -1) {
            uri += '?';
        }
        uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
    }
    HttpGet httpGet = new HttpGet(uri);
    if (httpProxy != null) {
        RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
        httpGet.setConfig(config);
    }
    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        Header[] contentTypeHeader = response.getHeaders("Content-Type");
        if (contentTypeHeader != null && contentTypeHeader.length > 0) {
            // 下载媒体文件出错
            if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) {
                String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
                throw new WxErrorException(WxError.fromJson(responseContent));
            }
        }
        InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);
        // 视频文件不支持下载
        String fileName = getFileName(response);
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        String[] name_ext = fileName.split("\\.");
        File localFile = FileUtils.createTmpFile(inputStream, name_ext[0], name_ext[1], tmpDirFile);
        return localFile;
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) Header(org.apache.http.Header) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) File(java.io.File) WxErrorException(me.chanjar.weixin.common.exception.WxErrorException)

Example 15 with WxErrorException

use of me.chanjar.weixin.common.exception.WxErrorException in project weixin-java-tools by chanjarster.

the class MediaUploadRequestExecutor method execute.

@Override
public WxMediaUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File file) throws WxErrorException, ClientProtocolException, IOException {
    HttpPost httpPost = new HttpPost(uri);
    if (httpProxy != null) {
        RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
        httpPost.setConfig(config);
    }
    if (file != null) {
        HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody("media", file).setMode(HttpMultipartMode.RFC6532).build();
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
    }
    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
        WxError error = WxError.fromJson(responseContent);
        if (error.getErrorCode() != 0) {
            throw new WxErrorException(error);
        }
        return WxMediaUploadResult.fromJson(responseContent);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) WxError(me.chanjar.weixin.common.bean.result.WxError) HttpEntity(org.apache.http.HttpEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) WxErrorException(me.chanjar.weixin.common.exception.WxErrorException)

Aggregations

WxErrorException (me.chanjar.weixin.common.exception.WxErrorException)28 WxError (me.chanjar.weixin.common.bean.result.WxError)19 RequestConfig (org.apache.http.client.config.RequestConfig)13 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 HashMap (java.util.HashMap)8 HttpPost (org.apache.http.client.methods.HttpPost)8 IOException (java.io.IOException)6 StringEntity (org.apache.http.entity.StringEntity)6 HttpGet (org.apache.http.client.methods.HttpGet)5 ClientProtocolException (org.apache.http.client.ClientProtocolException)4 JsonObject (com.google.gson.JsonObject)3 InputStream (java.io.InputStream)3 File (java.io.File)2 ExecutorService (java.util.concurrent.ExecutorService)2 WxAccessToken (me.chanjar.weixin.common.bean.WxAccessToken)2 RequestExecutor (me.chanjar.weixin.common.util.http.RequestExecutor)2 Header (org.apache.http.Header)2 BasicResponseHandler (org.apache.http.impl.client.BasicResponseHandler)2 DataProvider (org.testng.annotations.DataProvider)2 Test (org.testng.annotations.Test)2