Java Code Examples for me.chanjar.weixin.common.error.WxError#getErrorCode()

The following examples show how to use me.chanjar.weixin.common.error.WxError#getErrorCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OkHttpMediaUploadRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public WxMediaUploadResult execute(String uri, File file) throws WxErrorException, IOException {
  logger.debug("OkHttpMediaUploadRequestExecutor is running");
  //得到httpClient
  OkHttpClient client = requestHttp.getRequestHttpClient();

  RequestBody body = new MultipartBody.Builder()
    .setType(MediaType.parse("multipart/form-data"))
    .addFormDataPart("media",
      file.getName(),
      RequestBody.create(MediaType.parse("application/octet-stream"), file))
    .build();
  Request request = new Request.Builder().url(uri).post(body).build();

  Response response = client.newCall(request).execute();
  String responseContent = response.body().string();
  WxError error = WxError.fromJson(responseContent);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  }
  return WxMediaUploadResult.fromJson(responseContent);
}
 
Example 2
Source File: OkHttpSimpleGetRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public String execute(String uri, String queryParam) throws WxErrorException, IOException {
  logger.debug("OkHttpSimpleGetRequestExecutor is running");
  if (queryParam != null) {
    if (uri.indexOf('?') == -1) {
      uri += '?';
    }
    uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
  }

  //得到httpClient
  OkHttpClient client = requestHttp.getRequestHttpClient();
  Request request = new Request.Builder().url(uri).build();
  Response response = client.newCall(request).execute();
  String responseContent = response.body().string();
  WxError error = WxError.fromJson(responseContent);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  }
  return responseContent;
}
 
Example 3
Source File: MediaImgUploadOkhttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public WxMediaImgUploadResult execute(String uri, File file) throws WxErrorException, IOException {
  logger.debug("MediaImgUploadOkhttpRequestExecutor is running");
  //得到httpClient
  OkHttpClient client = requestHttp.getRequestHttpClient();

  RequestBody body = new MultipartBody.Builder()
    .setType(MediaType.parse("multipart/form-data"))
    .addFormDataPart("media",
      file.getName(),
      RequestBody.create(MediaType.parse("application/octet-stream"), file))
    .build();

  Request request = new Request.Builder().url(uri).post(body).build();
  Response response = client.newCall(request).execute();
  String responseContent = response.body().string();
  WxError error = WxError.fromJson(responseContent, WxType.MP);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  }

  return WxMediaImgUploadResult.fromJson(responseContent);
}
 
Example 4
Source File: WxOpenComponentServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private String get(String uri, String accessTokenKey) throws WxErrorException {
  String componentAccessToken = getComponentAccessToken(false);
  String uriWithComponentAccessToken = uri + (uri.contains("?") ? "&" : "?") + accessTokenKey + "=" + componentAccessToken;
  try {
    return getWxOpenService().get(uriWithComponentAccessToken, null);
  } catch (WxErrorException e) {
    WxError error = e.getError();
    /*
     * 发生以下情况时尝试刷新access_token
     * 40001 获取access_token时AppSecret错误,或者access_token无效
     * 42001 access_token超时
     * 40014 不合法的access_token,请开发者认真比对access_token的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口
     */
    if (error.getErrorCode() == 42001 || error.getErrorCode() == 40001 || error.getErrorCode() == 40014) {
      // 强制设置wxMpConfigStorage它的access token过期了,这样在下一次请求里就会刷新access token
      this.getWxOpenConfigStorage().expireComponentAccessToken();
      if (this.getWxOpenConfigStorage().autoRefreshToken()) {
        return this.get(uri, accessTokenKey);
      }
    }
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error, e);
    }
    return null;
  }
}
 
Example 5
Source File: WxMpUserTagServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public boolean batchTagging(Long tagId, String[] openids)
  throws WxErrorException {
  String url = API_URL_PREFIX + "/members/batchtagging";

  JsonObject json = new JsonObject();
  json.addProperty("tagid", tagId);
  JsonArray openidArrayJson = new JsonArray();
  for (String openid : openids) {
    openidArrayJson.add(openid);
  }
  json.add("openid_list", openidArrayJson);

  String responseContent = this.wxMpService.post(url, json.toString());
  WxError wxError = WxError.fromJson(responseContent, WxType.MP);
  if (wxError.getErrorCode() == 0) {
    return true;
  }

  throw new WxErrorException(wxError);
}
 
Example 6
Source File: MaterialVideoInfoApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpMaterialVideoInfoResult execute(String uri, String materialId) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpPost.setConfig(config);
  }

  Map<String, String> params = new HashMap<>();
  params.put("media_id", materialId);
  httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params)));
  try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent, WxType.MP);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    } else {
      return WxMpMaterialVideoInfoResult.fromJson(responseContent);
    }
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example 7
Source File: WxOpenComponentServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private String post(String uri, String postData, String accessTokenKey) throws WxErrorException {
  String componentAccessToken = getComponentAccessToken(false);
  String uriWithComponentAccessToken = uri + (uri.contains("?") ? "&" : "?") + accessTokenKey + "=" + componentAccessToken;
  try {
    return getWxOpenService().post(uriWithComponentAccessToken, postData);
  } catch (WxErrorException e) {
    WxError error = e.getError();
    /*
     * 发生以下情况时尝试刷新access_token
     * 40001 获取access_token时AppSecret错误,或者access_token无效
     * 42001 access_token超时
     * 40014 不合法的access_token,请开发者认真比对access_token的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口
     */
    if (error.getErrorCode() == 42001 || error.getErrorCode() == 40001 || error.getErrorCode() == 40014) {
      // 强制设置wxMpConfigStorage它的access token过期了,这样在下一次请求里就会刷新access token
      this.getWxOpenConfigStorage().expireComponentAccessToken();
      if (this.getWxOpenConfigStorage().autoRefreshToken()) {
        return this.post(uri, postData, accessTokenKey);
      }
    }
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error, e);
    }
    return null;
  }
}
 
Example 8
Source File: JoddHttpSimpleGetRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public String execute(String uri, String queryParam) throws WxErrorException, IOException {
  if (queryParam != null) {
    if (uri.indexOf('?') == -1) {
      uri += '?';
    }
    uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
  }

  HttpRequest request = HttpRequest.get(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
  }
  request.withConnectionProvider(requestHttp.getRequestHttpClient());
  HttpResponse response = request.send();
  response.charset(StringPool.UTF_8);

  String responseContent = response.bodyText();

  WxError error = WxError.fromJson(responseContent);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  }
  return responseContent;
}
 
Example 9
Source File: WxMpMaterialServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpMaterialCountResult materialCount() throws WxErrorException {
  String responseText = this.wxMpService.get(MATERIAL_GET_COUNT_URL, null);
  WxError wxError = WxError.fromJson(responseText, WxType.MP);
  if (wxError.getErrorCode() == 0) {
    return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialCountResult.class);
  } else {
    throw new WxErrorException(wxError);
  }
}
 
Example 10
Source File: WxMpMaterialServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public boolean materialNewsUpdate(WxMpMaterialArticleUpdate wxMpMaterialArticleUpdate) throws WxErrorException {
  String responseText = this.wxMpService.post(NEWS_UPDATE_URL, wxMpMaterialArticleUpdate.toJson());
  WxError wxError = WxError.fromJson(responseText, WxType.MP);
  if (wxError.getErrorCode() == 0) {
    return true;
  } else {
    throw new WxErrorException(wxError);
  }
}
 
Example 11
Source File: WxMpStoreServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> listCategories() throws WxErrorException {
  String response = this.wxMpService.get(POI_GET_WX_CATEGORY_URL, null);
  WxError wxError = WxError.fromJson(response, WxType.MP);
  if (wxError.getErrorCode() != 0) {
    throw new WxErrorException(wxError);
  }

  return WxMpGsonBuilder.create().fromJson(
    new JsonParser().parse(response).getAsJsonObject().get("category_list"),
    new TypeToken<List<String>>() {
    }.getType());
}
 
Example 12
Source File: WxMpStoreServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void update(WxMpStoreBaseInfo request) throws WxErrorException {
  String response = this.wxMpService.post(POI_UPDATE_URL, request.toJson());
  WxError wxError = WxError.fromJson(response, WxType.MP);
  if (wxError.getErrorCode() != 0) {
    throw new WxErrorException(wxError);
  }
}
 
Example 13
Source File: WxMaTemplateServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public boolean delTemplate(String templateId) throws WxErrorException {
  Map<String, String> params = new HashMap<>();
  params.put("template_id", templateId);

  String responseText = this.wxMaService.post(TEMPLATE_DEL_URL, WxGsonBuilder.create().toJson(params));
  WxError wxError = WxError.fromJson(responseText);
  if(wxError.getErrorCode() == 0){
    return true;
  }else {
    throw new WxErrorException(wxError);
  }
}
 
Example 14
Source File: WxMpStoreServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpStoreBaseInfo get(String poiId) throws WxErrorException {
  JsonObject paramObject = new JsonObject();
  paramObject.addProperty("poi_id", poiId);
  String response = this.wxMpService.post(POI_GET_URL, paramObject.toString());
  WxError wxError = WxError.fromJson(response, WxType.MP);
  if (wxError.getErrorCode() != 0) {
    throw new WxErrorException(wxError);
  }
  return WxMpStoreBaseInfo.fromJson(new JsonParser().parse(response).getAsJsonObject()
    .get("business").getAsJsonObject().get("base_info").toString());
}
 
Example 15
Source File: WxMpStoreServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void add(WxMpStoreBaseInfo request) throws WxErrorException {
  BeanUtils.checkRequiredFields(request);

  String response = this.wxMpService.post(POI_ADD_URL, request.toJson());
  WxError wxError = WxError.fromJson(response, WxType.MP);
  if (wxError.getErrorCode() != 0) {
    throw new WxErrorException(wxError);
  }
}
 
Example 16
Source File: WxMpServiceOkHttpImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
  this.log.debug("WxMpServiceOkHttpImpl is running");
  Lock lock = this.getWxMpConfigStorage().getAccessTokenLock();
  try {
    lock.lock();

    if (this.getWxMpConfigStorage().isAccessTokenExpired() || forceRefresh) {
      String url = String.format(WxMpService.GET_ACCESS_TOKEN_URL,
        this.getWxMpConfigStorage().getAppId(), this.getWxMpConfigStorage().getSecret());

      Request request = new Request.Builder().url(url).get().build();
      Response response = getRequestHttpClient().newCall(request).execute();
      String resultContent = response.body().string();
      WxError error = WxError.fromJson(resultContent, WxType.MP);
      if (error.getErrorCode() != 0) {
        throw new WxErrorException(error);
      }
      WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
      this.getWxMpConfigStorage().updateAccessToken(accessToken.getAccessToken(),
        accessToken.getExpiresIn());
    }
  } catch (IOException e) {
    this.log.error(e.getMessage(), e);
  } finally {
    lock.unlock();
  }
  return this.getWxMpConfigStorage().getAccessToken();
}
 
Example 17
Source File: MediaImgUploadApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMediaImgUploadResult execute(String uri, File data) throws WxErrorException, IOException {
  if (data == null) {
    throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("文件对象为空").build());
  }

  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpPost.setConfig(config);
  }

  HttpEntity entity = MultipartEntityBuilder
    .create()
    .addBinaryBody("media", data)
    .setMode(HttpMultipartMode.RFC6532)
    .build();
  httpPost.setEntity(entity);
  httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());

  try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent, WxType.MP);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }

    return WxMediaImgUploadResult.fromJson(responseContent);
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example 18
Source File: WxCpServiceApacheHttpClientImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
  if (this.configStorage.isAccessTokenExpired() || forceRefresh) {
    synchronized (this.globalAccessTokenRefreshLock) {
      if (this.configStorage.isAccessTokenExpired()) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?"
          + "&corpid=" + this.configStorage.getCorpId()
          + "&corpsecret=" + this.configStorage.getCorpSecret();
        try {
          HttpGet httpGet = new HttpGet(url);
          if (this.httpProxy != null) {
            RequestConfig config = RequestConfig.custom()
              .setProxy(this.httpProxy).build();
            httpGet.setConfig(config);
          }
          String resultContent = null;
          try (CloseableHttpClient httpclient = getRequestHttpClient();
               CloseableHttpResponse response = httpclient.execute(httpGet)) {
            resultContent = new BasicResponseHandler().handleResponse(response);
          } finally {
            httpGet.releaseConnection();
          }
          WxError error = WxError.fromJson(resultContent, WxType.CP);
          if (error.getErrorCode() != 0) {
            throw new WxErrorException(error);
          }
          WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
          this.configStorage.updateAccessToken(
            accessToken.getAccessToken(), accessToken.getExpiresIn());
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }
  return this.configStorage.getAccessToken();
}
 
Example 19
Source File: WxMpMaterialServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpMaterialNewsBatchGetResult materialNewsBatchGet(int offset, int count) throws WxErrorException {
  Map<String, Object> params = new HashMap<>();
  params.put("type", WxConsts.MaterialType.NEWS);
  params.put("offset", offset);
  params.put("count", count);
  String responseText = this.wxMpService.post(MATERIAL_BATCHGET_URL, WxGsonBuilder.create().toJson(params));
  WxError wxError = WxError.fromJson(responseText, WxType.MP);
  if (wxError.getErrorCode() == 0) {
    return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialNewsBatchGetResult.class);
  } else {
    throw new WxErrorException(wxError);
  }
}
 
Example 20
Source File: WxMpTemplateMsgSender.java    From WePush with MIT License 4 votes vote down vote up
@Override
public void completed(HttpResponse httpResponse) {
    BoostForm boostForm = BoostForm.getInstance();

    try {
        String response = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
        if (response.isEmpty()) {
            // 总发送失败+1
            PushData.increaseFail();
            boostForm.getFailCountLabel().setText(String.valueOf(PushData.failRecords));

            // 保存发送失败
            PushData.sendFailList.add(msgData);

            // 失败异常信息输出控制台
            ConsoleUtil.boostConsoleOnly("发送失败:" + WxError.builder().errorCode(9999).errorMsg("无响应内容").build() + ";msgData:" + JSONUtil.toJsonPrettyStr(msgData));
            // 总进度条
            boostForm.getCompletedProgressBar().setValue(PushData.successRecords.intValue() + PushData.failRecords.intValue());
        } else {
            WxError error = WxError.fromJson(response);
            if (error.getErrorCode() != 0) {
                // 总发送失败+1
                PushData.increaseFail();
                boostForm.getFailCountLabel().setText(String.valueOf(PushData.failRecords));

                // 保存发送失败
                PushData.sendFailList.add(msgData);

                // 失败异常信息输出控制台
                ConsoleUtil.boostConsoleOnly("发送失败:" + error + ";msgData:" + JSONUtil.toJsonPrettyStr(msgData));
                // 总进度条
                boostForm.getCompletedProgressBar().setValue(PushData.successRecords.intValue() + PushData.failRecords.intValue());
            } else {
                // 已成功+1
                PushData.increaseSuccess();
                boostForm.getSuccessCountLabel().setText(String.valueOf(PushData.successRecords));

                // 保存发送成功
                PushData.sendSuccessList.add(msgData);
                // 总进度条
                boostForm.getCompletedProgressBar().setValue(PushData.successRecords.intValue() + PushData.failRecords.intValue());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}