me.chanjar.weixin.common.WxType Java Examples

The following examples show how to use me.chanjar.weixin.common.WxType. 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: MediaImgUploadHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 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());
  }

  HttpRequest request = HttpRequest.post(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
  }
  request.withConnectionProvider(requestHttp.getRequestHttpClient());

  request.form("media", data);
  HttpResponse response = request.send();
  response.charset(StringPool.UTF_8);
  String responseContent = response.bodyText();
  WxError error = WxError.fromJson(responseContent, WxType.MP);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  }

  return WxMediaImgUploadResult.fromJson(responseContent);
}
 
Example #2
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 #3
Source File: MaterialVideoInfoOkhttpRequestExecutor.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 {
  logger.debug("MaterialVideoInfoOkhttpRequestExecutor is running");
  //得到httpClient
  OkHttpClient client = requestHttp.getRequestHttpClient();

  RequestBody requestBody = new FormBody.Builder().add("media_id", materialId).build();
  Request request = new Request.Builder().url(uri).post(requestBody).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);
  } else {
    return WxMpMaterialVideoInfoResult.fromJson(responseContent);
  }
}
 
Example #4
Source File: MaterialDeleteApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean 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 true;
    }
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example #5
Source File: MaterialNewsInfoApacheHttpRequestExecutor.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 {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpPost.setConfig(config);
  }

  httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(ImmutableMap.of("media_id", materialId))));
  try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    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);
    }
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example #6
Source File: MaterialDeleteJoddHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean execute(String uri, String materialId) throws WxErrorException, IOException {
  HttpRequest request = HttpRequest.post(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
  }
  request.withConnectionProvider(requestHttp.getRequestHttpClient());

  request.query("media_id", materialId);
  HttpResponse response = request.send();
  response.charset(StringPool.UTF_8);
  String responseContent = response.bodyText();
  WxError error = WxError.fromJson(responseContent, WxType.MP);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  } else {
    return true;
  }
}
 
Example #7
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 #8
Source File: MaterialDeleteOkhttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean execute(String uri, String materialId) throws WxErrorException, IOException {
  logger.debug("MaterialDeleteOkhttpRequestExecutor is running");
  //得到httpClient
  OkHttpClient client = requestHttp.getRequestHttpClient();

  RequestBody requestBody = new FormBody.Builder().add("media_id", materialId).build();
  Request request = new Request.Builder().url(uri).post(requestBody).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);
  } else {
    return true;
  }
}
 
Example #9
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 #10
Source File: WxMpUserTagServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public boolean batchUntagging(Long tagId, String[] openids)
  throws WxErrorException {
  String url = API_URL_PREFIX + "/members/batchuntagging";

  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 #11
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 #12
Source File: WxMpUserTagServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean tagDelete(Long id) throws WxErrorException {
  String url = API_URL_PREFIX + "/delete";

  JsonObject json = new JsonObject();
  JsonObject tagJson = new JsonObject();
  tagJson.addProperty("id", id);
  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 #13
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 #14
Source File: MaterialVideoInfoJoddHttpRequestExecutor.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 {
  HttpRequest request = HttpRequest.post(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
  }
  request.withConnectionProvider(requestHttp.getRequestHttpClient());

  request.query("media_id", materialId);
  HttpResponse response = request.send();
  response.charset(StringPool.UTF_8);
  String responseContent = response.bodyText();
  WxError error = WxError.fromJson(responseContent, WxType.MP);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  } else {
    return WxMpMaterialVideoInfoResult.fromJson(responseContent);
  }
}
 
Example #15
Source File: MaterialVoiceAndImageDownloadOkhttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream execute(String uri, String materialId) throws WxErrorException, IOException {
  logger.debug("MaterialVoiceAndImageDownloadOkhttpRequestExecutor is running");
  OkHttpClient client = requestHttp.getRequestHttpClient();
  RequestBody requestBody = new FormBody.Builder().add("media_id", materialId).build();
  Request request = new Request.Builder().url(uri).get().post(requestBody).build();
  Response response = client.newCall(request).execute();
  String contentTypeHeader = response.header("Content-Type");
  if ("text/plain".equals(contentTypeHeader)) {
    String responseContent = response.body().string();
    throw new WxErrorException(WxError.fromJson(responseContent, WxType.MP));
  }
  try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); BufferedSink sink = Okio.buffer(Okio.sink(outputStream))) {
    sink.writeAll(response.body().source());
    return new ByteArrayInputStream(outputStream.toByteArray());
  }
}
 
Example #16
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 #17
Source File: MaterialUploadOkhttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpMaterialUploadResult execute(String uri, WxMpMaterial material) throws WxErrorException, IOException {
  logger.debug("MaterialUploadOkhttpRequestExecutor is running");
  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();
  }

  //得到httpClient

  OkHttpClient client = requestHttp.getRequestHttpClient();

  MultipartBody.Builder bodyBuilder = new MultipartBody.Builder()
    .setType(MediaType.parse("multipart/form-data"))
    .addFormDataPart("media",
      file.getName(),
      RequestBody.create(MediaType.parse("application/octet-stream"), file));
  Map<String, String> form = material.getForm();
  if (form != null) {
    bodyBuilder.addFormDataPart("description", WxGsonBuilder.create().toJson(form));
  }

  Request request = new Request.Builder().url(uri).post(bodyBuilder.build()).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);
  } else {
    return WxMpMaterialUploadResult.fromJson(responseContent);
  }
}
 
Example #18
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 #19
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 #20
Source File: VoiceUploadApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean 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 true;
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example #21
Source File: QrCodeOkhttpRequestExecutor.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 {
  logger.debug("QrCodeOkhttpRequestExecutor is running");

  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");
  }

  OkHttpClient client = requestHttp.getRequestHttpClient();
  Request request = new Request.Builder().url(uri).get().build();
  Response response = client.newCall(request).execute();
  String contentTypeHeader = response.header("Content-Type");
  if ("text/plain".equals(contentTypeHeader)) {
    String responseContent = response.body().string();
    throw new WxErrorException(WxError.fromJson(responseContent, WxType.MP));
  }

  try (InputStream inputStream = response.body().byteStream()) {
    return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg");
  }

}
 
Example #22
Source File: QrCodeJoddHttpRequestExecutor.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");
  }

  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 contentTypeHeader = response.header("Content-Type");
  if (MimeTypes.MIME_TEXT_PLAIN.equals(contentTypeHeader)) {
    String responseContent = response.bodyText();
    throw new WxErrorException(WxError.fromJson(responseContent, WxType.MP));
  }
  try (InputStream inputStream = new ByteArrayInputStream(response.bodyBytes())) {
    return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg");
  }
}
 
Example #23
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 #24
Source File: WxMpMaterialServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public WxMpMaterialFileBatchGetResult materialFileBatchGet(String type, int offset, int count) throws WxErrorException {
  Map<String, Object> params = new HashMap<>();
  params.put("type", type);
  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, WxMpMaterialFileBatchGetResult.class);
  } else {
    throw new WxErrorException(wxError);
  }
}
 
Example #25
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 #26
Source File: WxCpServiceJoddHttpImpl.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();

        HttpRequest request = HttpRequest.get(url);
        if (this.httpProxy != null) {
          httpClient.useProxy(this.httpProxy);
        }
        request.withConnectionProvider(httpClient);
        HttpResponse response = request.send();

        String resultContent = response.bodyText();
        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());
      }
    }
  }
  return this.configStorage.getAccessToken();
}
 
Example #27
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 #28
Source File: WxMpTemplateMsgServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public String sendTemplateMsg(WxMpTemplateMessage templateMessage) throws WxErrorException {
  String url = "https://api.weixin.qq.com/cgi-bin/message/template/send";
  String responseContent = this.wxMpService.post(url, templateMessage.toJson());
  final JsonObject jsonObject = JSON_PARSER.parse(responseContent).getAsJsonObject();
  if (jsonObject.get("errcode").getAsInt() == 0) {
    return jsonObject.get("msgid").getAsString();
  }
  throw new WxErrorException(WxError.fromJson(responseContent, WxType.MP));
}
 
Example #29
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 #30
Source File: WxMpTemplateMsgServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public boolean delPrivateTemplate(String templateId) throws WxErrorException {
  String url = API_URL_PREFIX + "/del_private_template";
  JsonObject jsonObject = new JsonObject();
  jsonObject.addProperty("template_id", templateId);
  String responseContent = this.wxMpService.post(url, jsonObject.toString());
  WxError error = WxError.fromJson(responseContent, WxType.MP);
  if (error.getErrorCode() == 0) {
    return true;
  }

  throw new WxErrorException(error);
}