Search in sources :

Example 1 with MediaJsonRtn

use of org.usc.wechat.mp.sdk.vo.media.MediaJsonRtn in project wechat-mp-sdk by usc.

the class MediaUtil method uploadMedia.

// TODO-Shunli: now upload video always failed, tip system error, check later
public static MediaJsonRtn uploadMedia(License license, MediaFile mediaFile) {
    if (mediaFile == null) {
        return JsonRtnUtil.buildFailureJsonRtn(MediaJsonRtn.class, "missing mediaFile");
    }
    // maybe todo more mediaFile legality check
    String accessToken = AccessTokenUtil.getAccessToken(license);
    String url = WechatRequest.UPLOAD_MEDIA.getUrl();
    try {
        MediaType mediaType = mediaFile.getMediaType();
        URI uri = new URIBuilder(url).setParameter("access_token", accessToken).setParameter("type", mediaType.getName()).build();
        HttpEntity httpEntity = MultipartEntityBuilder.create().addBinaryBody("body", mediaFile.getFile()).build();
        String rtnJson = Request.Post(uri).connectTimeout(HttpUtil.CONNECT_TIMEOUT).socketTimeout(HttpUtil.SOCKET_TIMEOUT).body(httpEntity).execute().handleResponse(HttpUtil.UTF8_CONTENT_HANDLER);
        MediaJsonRtn jsonRtn = JsonRtnUtil.parseJsonRtn(rtnJson, MediaJsonRtn.class);
        log.info("upload media:\n url={},\n body={},\n rtn={},{}", uri, mediaFile, rtnJson, jsonRtn);
        return jsonRtn;
    } catch (Exception e) {
        String msg = "upload media failed:\n " + "url=" + url + "?access_token=" + accessToken + ",\n body=" + mediaFile;
        log.error(msg, e);
        return JsonRtnUtil.buildFailureJsonRtn(MediaJsonRtn.class, "uploadMedia failed");
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) MediaJsonRtn(org.usc.wechat.mp.sdk.vo.media.MediaJsonRtn) MediaType(org.usc.wechat.mp.sdk.vo.media.MediaType) URI(java.net.URI) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) URIBuilder(org.apache.http.client.utils.URIBuilder)

Aggregations

FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 URI (java.net.URI)1 HttpEntity (org.apache.http.HttpEntity)1 URIBuilder (org.apache.http.client.utils.URIBuilder)1 MediaJsonRtn (org.usc.wechat.mp.sdk.vo.media.MediaJsonRtn)1 MediaType (org.usc.wechat.mp.sdk.vo.media.MediaType)1