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

The following examples show how to use me.chanjar.weixin.common.error.WxError#fromJson() . 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: MaterialNewsInfoJoddHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpMaterialNews execute(String uri, String materialId) throws WxErrorException, IOException {
  if (requestHttp.getRequestHttpProxy() != null) {
    requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
  }

  HttpRequest request = HttpRequest.post(uri)
    .withConnectionProvider(requestHttp.getRequestHttpClient())
    .body(WxGsonBuilder.create().toJson(ImmutableMap.of("media_id", materialId)));
  HttpResponse response = request.send();
  response.charset(StringPool.UTF_8);

  String responseContent = response.bodyText();
  this.logger.debug("响应原始数据:{}", responseContent);
  WxError error = WxError.fromJson(responseContent, WxType.MP);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  } else {
    return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class);
  }
}
 
Example 2
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 3
Source File: MaterialNewsInfoOkhttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpMaterialNews execute(String uri, String materialId) throws WxErrorException, IOException {

  //得到httpClient
  OkHttpClient client = requestHttp.getRequestHttpClient();

  RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),
    WxGsonBuilder.create().toJson(ImmutableMap.of("media_id", materialId)));
  Request request = new Request.Builder().url(uri).post(requestBody).build();

  Response response = client.newCall(request).execute();
  String responseContent = response.body().string();
  this.logger.debug("响应原始数据:{}", responseContent);

  WxError error = WxError.fromJson(responseContent, WxType.MP);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  } else {
    return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class);
  }
}
 
Example 4
Source File: WxMpUserTagServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean tagUpdate(Long id, String name) throws WxErrorException {
  String url = API_URL_PREFIX + "/update";

  JsonObject json = new JsonObject();
  JsonObject tagJson = new JsonObject();
  tagJson.addProperty("id", id);
  tagJson.addProperty("name", name);
  json.add("tag", tagJson);

  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 5
Source File: WxMpStoreServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(String poiId) throws WxErrorException {
  JsonObject paramObject = new JsonObject();
  paramObject.addProperty("poi_id", poiId);
  String response = this.wxMpService.post(POI_DEL_URL, paramObject.toString());
  WxError wxError = WxError.fromJson(response, WxType.MP);
  if (wxError.getErrorCode() != 0) {
    throw new WxErrorException(wxError);
  }
}
 
Example 6
Source File: WxMaTemplateServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMaTemplateListResult findTemplateList(int offset, int count) throws WxErrorException {

  Map<String, Integer> params = new HashMap<>();
  params.put("offset", offset);
  params.put("count", count);

  String responseText = this.wxMaService.post(TEMPLATE_LIST_URL, WxGsonBuilder.create().toJson(params));
  WxError wxError = WxError.fromJson(responseText);
  if(wxError.getErrorCode() == 0){
    return WxMaTemplateListResult.fromJson(responseText);
  }else {
    throw new WxErrorException(wxError);
  }
}
 
Example 7
Source File: WxMpAiOpenServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String queryRecognitionResult(String voiceId, AiLangType lang) throws WxErrorException {
  if (lang == null) {
    lang = AiLangType.zh_CN;
  }

  final String responseContent = this.wxMpService.get(VOICE_QUERY_RESULT_URL,
    String.format("voice_id=%s&lang=%s", voiceId, lang.getCode()));
  final JsonObject jsonObject = JSON_PARSER.parse(responseContent).getAsJsonObject();
  if (jsonObject.get("errcode") == null || jsonObject.get("errcode").getAsInt() == 0) {
    return jsonObject.get("result").getAsString();
  }

  throw new WxErrorException(WxError.fromJson(responseContent, WxType.MP));
}
 
Example 8
Source File: WxMpAiOpenServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String translate(AiLangType langFrom, AiLangType langTo, String content) throws WxErrorException {
  final String responseContent = this.wxMpService.post(String.format(TRANSLATE_URL, langFrom.getCode(), langTo.getCode()),
    content);
  final JsonObject jsonObject = new JsonParser().parse(responseContent).getAsJsonObject();
  if (jsonObject.get("errcode") == null || jsonObject.get("errcode").getAsInt() == 0) {
    return jsonObject.get("to_content").getAsString();
  }

  throw new WxErrorException(WxError.fromJson(responseContent, WxType.MP));
}
 
Example 9
Source File: WxMaTemplateServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMaTemplateLibraryListResult findTemplateLibraryList(int offset, int count) throws WxErrorException {

  Map<String, Integer> params = new HashMap<>();
  params.put("offset", offset);
  params.put("count", count);

  String responseText = this.wxMaService.post(TEMPLATE_LIBRARY_LIST_URL, WxGsonBuilder.create().toJson(params));
  WxError wxError = WxError.fromJson(responseText);
  if(wxError.getErrorCode() == 0){
    return WxMaTemplateLibraryListResult.fromJson(responseText);
  }else {
    throw new WxErrorException(wxError);
  }
}
 
Example 10
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 11
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 12
Source File: WxMpShakeServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxError deviceBindPageQuery(WxMpShakeAroundDeviceBindPageQuery shakeAroundDeviceBindPageQuery) throws WxErrorException {
  String url = "https://api.weixin.qq.com/shakearound/device/bindpage";
  String postData = shakeAroundDeviceBindPageQuery.toJsonString();
  String responseContent = this.wxMpService.post(url, postData);
  return WxError.fromJson(responseContent, WxType.MP);
}
 
Example 13
Source File: QrCodeApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public File execute(String uri, WxMpQrCodeTicket ticket) throws WxErrorException, 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 (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpGet.setConfig(config);
  }

  try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpGet);
       InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);) {
    Header[] contentTypeHeader = response.getHeaders("Content-Type");
    if (contentTypeHeader != null && contentTypeHeader.length > 0) {
      // 出错
      if (ContentType.TEXT_PLAIN.getMimeType()
        .equals(ContentType.parse(contentTypeHeader[0].getValue()).getMimeType())) {
        String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
        throw new WxErrorException(WxError.fromJson(responseContent, WxType.MP));
      }
    }
    return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg");
  } finally {
    httpGet.releaseConnection();
  }
}
 
Example 14
Source File: WxMaTemplateServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMaTemplateAddResult addTemplate(String id, List<Integer> keywordIdList) throws WxErrorException {

  Map<String, Object> params = new HashMap<>();
  params.put("id", id);
  params.put("keyword_id_list", keywordIdList.toArray());

  String responseText = this.wxMaService.post(TEMPLATE_ADD_URL, WxGsonBuilder.create().toJson(params));
  WxError wxError = WxError.fromJson(responseText);
  if(wxError.getErrorCode() == 0){
    return WxMaTemplateAddResult.fromJson(responseText);
  }else {
    throw new WxErrorException(wxError);
  }
}
 
Example 15
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 16
Source File: WxMpTemplateMsgServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String addTemplate(String shortTemplateId) throws WxErrorException {
  String url = API_URL_PREFIX + "/api_add_template";
  JsonObject jsonObject = new JsonObject();
  jsonObject.addProperty("template_id_short", shortTemplateId);
  String responseContent = this.wxMpService.post(url, jsonObject.toString());
  final JsonObject result = JSON_PARSER.parse(responseContent).getAsJsonObject();
  if (result.get("errcode").getAsInt() == 0) {
    return result.get("template_id").getAsString();
  }

  throw new WxErrorException(WxError.fromJson(responseContent, WxType.MP));
}
 
Example 17
Source File: OkHttpMediaDownloadRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public File execute(String uri, String queryParam) throws WxErrorException, IOException {
  logger.debug("OkHttpMediaDownloadRequestExecutor 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).get().build();

  Response response = client.newCall(request).execute();

  String contentType = response.header("Content-Type");
  if (contentType != null && contentType.startsWith("application/json")) {
    // application/json; encoding=utf-8 下载媒体文件出错
    throw new WxErrorException(WxError.fromJson(response.body().string()));
  }

  String fileName = new HttpResponseProxy(response).getFileName();
  if (StringUtils.isBlank(fileName)) {
    return null;
  }

  File file = File.createTempFile(
    FilenameUtils.getBaseName(fileName), "." + FilenameUtils.getExtension(fileName), super.tmpDirFile
  );

  try (BufferedSink sink = Okio.buffer(Okio.sink(file))) {
    sink.writeAll(response.body().source());
  }

  file.deleteOnExit();
  return file;
}
 
Example 18
Source File: ApacheSimplePostRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String execute(String uri, String postEntity) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpPost.setConfig(config);
  }

  if (postEntity != null) {
    StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
    httpPost.setEntity(entity);
  }

  try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    if (responseContent.isEmpty()) {
      throw new WxErrorException(WxError.builder().errorCode(9999).errorMsg("无响应内容").build());
    }

    if (responseContent.startsWith("<xml>")) {
      //xml格式输出直接返回
      return responseContent;
    }

    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }
    return responseContent;
  } finally {
    httpPost.releaseConnection();
  }
}
 
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: MaterialUploadApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
@Override
public WxMpMaterialUploadResult execute(String uri, WxMpMaterial material) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig response = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpPost.setConfig(response);
  }

  if (material == null) {
    throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("非法请求,material参数为空").build());
  }

  File file = material.getFile();
  if (file == null || !file.exists()) {
    throw new FileNotFoundException();
  }

  MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
  multipartEntityBuilder
    .addBinaryBody("media", file)
    .setMode(HttpMultipartMode.RFC6532);
  Map<String, String> form = material.getForm();
  if (material.getForm() != null) {
    multipartEntityBuilder.addPart("description",
      new StringBody(WxGsonBuilder.create().toJson(form), ContentType.create("text/plain", Consts.UTF_8)));
  }

  httpPost.setEntity(multipartEntityBuilder.build());
  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);
    } else {
      return WxMpMaterialUploadResult.fromJson(responseContent);
    }
  } finally {
    httpPost.releaseConnection();
  }
}