me.chanjar.weixin.common.error.WxError Java Examples

The following examples show how to use me.chanjar.weixin.common.error.WxError. 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: 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 #2
Source File: ApacheHttpClientSimpleGetRequestExecutor.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;
  }
  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)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }
    return responseContent;
  } finally {
    httpGet.releaseConnection();
  }
}
 
Example #3
Source File: ApacheMediaUploadRequestExecutor.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 {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
    httpPost.setConfig(config);
  }
  if (file != null) {
    HttpEntity entity = MultipartEntityBuilder
      .create()
      .addBinaryBody("media", file)
      .setMode(HttpMultipartMode.RFC6532)
      .build();
    httpPost.setEntity(entity);
  }
  try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().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);
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example #4
Source File: WxMpCardServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public String getCardDetail(String cardId) throws WxErrorException {
  JsonObject param = new JsonObject();
  param.addProperty("card_id", cardId);
  String responseContent = this.wxMpService.post(CARD_GET, param.toString());

  // 判断返回值
  JsonObject json = (new JsonParser()).parse(responseContent).getAsJsonObject();
  String errcode = json.get("errcode").getAsString();
  if (!"0".equals(errcode)) {
    String errmsg = json.get("errmsg").getAsString();
    throw new WxErrorException(WxError.builder()
      .errorCode(Integer.valueOf(errcode)).errorMsg(errmsg)
      .build());
  }

  return responseContent;
}
 
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: WxCpBusyRetryTest.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@DataProvider(name = "getService")
public Object[][] getService() {
  WxCpService service = new WxCpServiceImpl() {

    @Override
    public synchronized <T, E> T executeInternal(
      RequestExecutor<T, E> executor, String uri, E data)
      throws WxErrorException {
      this.log.info("Executed");
      throw new WxErrorException(WxError.builder().errorCode(-1).build());
    }
  };

  service.setMaxRetryTimes(3);
  service.setRetrySleepMillis(500);
  return new Object[][]{
    new Object[]{service}
  };
}
 
Example #7
Source File: WxErrorAdapter.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public WxError deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
  throws JsonParseException {
  WxError.WxErrorBuilder errorBuilder = WxError.builder();
  JsonObject wxErrorJsonObject = json.getAsJsonObject();

  if (wxErrorJsonObject.get("errcode") != null && !wxErrorJsonObject.get("errcode").isJsonNull()) {
    errorBuilder.errorCode(GsonHelper.getAsPrimitiveInt(wxErrorJsonObject.get("errcode")));
  }
  if (wxErrorJsonObject.get("errmsg") != null && !wxErrorJsonObject.get("errmsg").isJsonNull()) {
    errorBuilder.errorMsg(GsonHelper.getAsString(wxErrorJsonObject.get("errmsg")));
  }

  errorBuilder.json(json.toString());

  return errorBuilder.build();
}
 
Example #8
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 #9
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 #10
Source File: JoddHttpMediaUploadRequestExecutor.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 {
  HttpRequest request = HttpRequest.post(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
  }
  request.withConnectionProvider(requestHttp.getRequestHttpClient());
  request.form("media", file);
  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 WxMediaUploadResult.fromJson(responseContent);
}
 
Example #11
Source File: WxMpKefuServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpKfMsgList kfMsgList(Date startTime, Date endTime, Long msgId, Integer number) throws WxErrorException {
  if (number > 10000) {
    throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("非法参数请求,每次最多查询10000条记录!").build());
  }

  if (startTime.after(endTime)) {
    throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("起始时间不能晚于结束时间!").build());
  }

  JsonObject param = new JsonObject();
  param.addProperty("starttime", startTime.getTime() / 1000); //starttime	起始时间,unix时间戳
  param.addProperty("endtime", endTime.getTime() / 1000); //endtime	结束时间,unix时间戳,每次查询时段不能超过24小时
  param.addProperty("msgid", msgId); //msgid	消息id顺序从小到大,从1开始
  param.addProperty("number", number); //number	每次获取条数,最多10000条

  String responseContent = this.wxMpService.post(MSGRECORD_GET_MSG_LIST, param.toString());

  return WxMpKfMsgList.fromJson(responseContent);
}
 
Example #12
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 #13
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 #14
Source File: OkHttpSimplePostRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public String execute(String uri, String postEntity) throws WxErrorException, IOException {
  logger.debug("OkHttpSimplePostRequestExecutor running");
  //得到httpClient
  OkHttpClient client = requestHttp.getRequestHttpClient();

  MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
  RequestBody body = RequestBody.create(mediaType, postEntity);

  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 responseContent;
}
 
Example #15
Source File: WxMaCodeServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] getQrCode() throws WxErrorException {
  String appId = this.wxMaService.getWxMaConfig().getAppid();
  Path qrCodeFilePath = null;
  try {
    RequestExecutor<File, String> executor = BaseMediaDownloadRequestExecutor
      .create(this.wxMaService.getRequestHttp(), Files.createTempDirectory("weixin-java-tools-ma-" + appId).toFile());
    qrCodeFilePath = this.wxMaService.execute(executor, GET_QRCODE_URL, null).toPath();
    return Files.readAllBytes(qrCodeFilePath);
  } catch (IOException e) {
    throw new WxErrorException(WxError.builder().errorMsg(e.getMessage()).build(), e);
  } finally {
    if (qrCodeFilePath != null) {
      try {
        // 及时删除二维码文件,避免积压过多缓存文件
        Files.delete(qrCodeFilePath);
      } catch (Exception ignored) {
      }
    }
  }
}
 
Example #16
Source File: WxMpQrcodeServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpQrCodeTicket qrCodeCreateLastTicket(int sceneId) throws WxErrorException {
  if (sceneId < 1 || sceneId > 100000) {
    throw new WxErrorException(WxError.builder().errorCode(-1)
      .errorMsg("永久二维码的场景值目前只支持1--100000!")
      .build());
  }

  String url = API_URL_PREFIX + "/create";
  JsonObject json = new JsonObject();
  json.addProperty("action_name", "QR_LIMIT_SCENE");
  JsonObject actionInfo = new JsonObject();
  JsonObject scene = new JsonObject();
  scene.addProperty("scene_id", sceneId);
  actionInfo.add("scene", scene);
  json.add("action_info", actionInfo);
  String responseContent = this.wxMpService.post(url, json.toString());
  return WxMpQrCodeTicket.fromJson(responseContent);
}
 
Example #17
Source File: WxMpBusyRetryTest.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@DataProvider(name = "getService")
public Object[][] getService() {
  WxMpService service = new WxMpServiceHttpClientImpl() {

    @Override
    public synchronized <T, E> T executeInternal(
      RequestExecutor<T, E> executor, String uri, E data)
      throws WxErrorException {
      this.log.info("Executed");
      throw new WxErrorException(WxError.builder().errorCode(-1).build());
    }
  };

  service.setMaxRetryTimes(3);
  service.setRetrySleepMillis(500);
  return new Object[][]{{service}};
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
Source File: MaterialVoiceAndImageDownloadApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream 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);
       InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response)) {
    // 下载媒体文件出错
    byte[] responseContent = IOUtils.toByteArray(inputStream);
    String responseContentString = new String(responseContent, StandardCharsets.UTF_8);
    if (responseContentString.length() < 100) {
      try {
        WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class);
        if (wxError.getErrorCode() != 0) {
          throw new WxErrorException(wxError);
        }
      } catch (com.google.gson.JsonSyntaxException ex) {
        return new ByteArrayInputStream(responseContent);
      }
    }
    return new ByteArrayInputStream(responseContent);
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example #30
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;
}