获取永久素材。

        :param media_id: 媒体文件 ID
        :return: requests 的 Response 实例
327162
def download_permanent_media(self, media_id):
        
        return requests.post(
            url="https://api.weixin.qq.com/cgi-bin/material/get_material",
            params={"access_token": self.token},
            data=_json.dumps({
                "media_id": media_id
            }, ensure_ascii=False).encode("utf-8")
        )
435769
def get_file_by_id(self, file_id):
        
        return self._create_item_response(
            self.data_service.get_file(file_id),
            File
        )
320713
public function getMediaWithHttpInfo($media_id, $is_video = false)
    {
        if (!$this->access_token && !$this->getAccessToken()) {
            return false;
        }
        $url_prefix = $is_video ? str_replace('https', 'http', self::API_URL_PREFIX) : self::API_URL_PREFIX;
        $url = $url_prefix . self::MEDIA_GET_URL . "access_token={$this->access_token}" . '&media_id=' . $media_id;
        $oCurl = curl_init();
        if (stripos($url, "https://") !== false) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        $result = array();
        if (intval($aStatus["http_code"]) !== 200) {
            return false;
        }
        if ($sContent) {
            if (is_string($sContent)) {
                $json = json_decode($sContent, true);
                if (isset($json['errcode'])) {
                    $this->errCode = $json['errcode'];
                    $this->errMsg = $json['errmsg'];
                    return $this->checkRetry(__FUNCTION__, func_get_args());
                }
            }
            $result['content'] = $sContent;
            $result['info'] = $aStatus;
            return $result;
        }
        return false;
    }
1042479
def info(self, media_id):
        
        dr = self.__app.native_api_call('media', 'i/' + media_id, {}, self.__options, False, None, False, http_path="/api/meta/v1/", http_method='GET')
        return json.loads(dr.text)
217255
def anime(self, item_id):
        
        query_string = """\
            query ($id: Int) {
                Media(id: $id, type: ANIME) {
                    title {
                        romaji
                        english
                    }
                    startDate {
                        year
                        month
                        day
                    }
                    endDate {
                        year
                        month
                        day
                    }
                    coverImage {
                        large
                    }
                    bannerImage
                    format
                    status
                    episodes
                    season
                    description
                    averageScore
                    meanScore
                    genres
                    synonyms
                    nextAiringEpisode {
                        airingAt
                        timeUntilAiring
                        episode
                    }
                }
            }
        """
        vars = {"id": item_id}
        r = requests.post(self.settings['apiurl'],
                         headers=self.settings['header'],
                         json={'query': query_string, 'variables': vars})
        jsd = r.text

        try:
            jsd = json.loads(jsd)
        except ValueError:
            return None
        else:
            return jsd
551379
public function openidVoice($media_id = '', $openids = [])
    {
        $queryStr                      = [];
        $queryStr['touser']            = $openids;
        $queryStr['voice']['media_id'] = $media_id;
        $queryStr['msgtype']           = 'voice';

        $this->module = 'message';

        $res = $this->_post('mass/send', $queryStr);

        return $res;
    }
399388
public GetMediaSourceDownloadResponse getMediaSourceDownload(GetMediaSourceDownloadRequest request) {

        checkStringNotEmpty(request.getMediaId(), "Media ID should not be null or empty!");

        InternalRequest internalRequest =
                createRequest(HttpMethodName.GET, request, PATH_MEDIA, request.getMediaId());
        internalRequest.addParameter(PARA_DOWNLOAD, null);
        internalRequest.addParameter(PARA_EXPIREDINSECONDS, String.valueOf(request.getExpiredInSeconds()));

        return invokeHttpClient(internalRequest, GetMediaSourceDownloadResponse.class);
    }
208369
def group_id(self, resource_id):
        
        if self._name != 'group':
            self._request_uri = '{}/{}'.format(self._api_uri, resource_id)
109900
public GenerateMediaDeliveryInfoResponse generateMediaDeliveryInfo(String mediaId, String transcodingPresetName) {
        GenerateMediaDeliveryInfoRequest request = new GenerateMediaDeliveryInfoRequest()
                .withMediaId(mediaId)
                .withTranscodingPresetName(transcodingPresetName);
        return generateMediaDeliveryInfo(request);
    }
597851
public function updateForeverArticles($media_id,$data,$index=0){
        if (!$this->access_token && !$this->checkAuth()) return false;
        if (!isset($data['media_id'])) $data['media_id'] = $media_id;
        if (!isset($data['index'])) $data['index'] = $index;
        $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_NEWS_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return $json;
        }
        return false;
    }
223459
public static MediaGetResult mediaGet(String access_token,String media_id,boolean use_http){
		String http_s = use_http?BASE_URI.replace("https", "http"):BASE_URI;
		HttpUriRequest httpUriRequest = RequestBuilder.get()
					.setUri(http_s + "/cgi-bin/media/get")
					.addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
					.addParameter("media_id", media_id)
					.build();
		return LocalHttpClient.execute(httpUriRequest,BytesOrJsonResponseHandler.createResponseHandler(MediaGetResult.class));
	}
237079
public DownloadMaterialResponse downloadMaterial(String mediaId, MaterialType type){
        DownloadMaterialResponse response = new DownloadMaterialResponse();
        String url = BASE_API_URL + "cgi-bin/material/get_material?access_token=" + config.getAccessToken();
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(NetWorkCenter.CONNECT_TIMEOUT).setConnectTimeout(NetWorkCenter.CONNECT_TIMEOUT).setSocketTimeout(NetWorkCenter.CONNECT_TIMEOUT).build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        HttpPost request = new HttpPost(url);
        StringEntity mediaEntity = new StringEntity("{\"media_id\":\"" + mediaId + "\"}", ContentType.APPLICATION_JSON);
        request.setEntity(mediaEntity);

        CloseableHttpResponse httpResponse = null;
        try{
            httpResponse = client.execute(request);
            if(HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()){
                HttpEntity entity;
                String resultJson;
                switch (type){
                    case NEWS:
                        entity = httpResponse.getEntity();
                        resultJson = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                        response = JSONUtil.toBean(resultJson, DownloadMaterialResponse.class);
                        LOG.debug("-----------------请求成功-----------------");
                        LOG.debug("响应结果:");
                        LOG.debug(resultJson);
                        if (StrUtil.isBlank(response.getErrcode())) {
                            response.setErrcode("0");
                            response.setErrmsg(resultJson);
                        }
                        break;
                    case VIDEO:
                        entity = httpResponse.getEntity();
                        resultJson = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                        LOG.debug("-----------------请求成功-----------------");
                        LOG.debug("响应结果:");
                        LOG.debug(resultJson);
                        response = JSONUtil.toBean(resultJson, DownloadMaterialResponse.class);
                        if (StrUtil.isBlank(response.getErrcode())) {
                            response.setErrcode("0");
                            response.setErrmsg(resultJson);
                            // 通过down_url下载文件。文件放置在content中。通过writeTo方法获取
                            downloadVideo(response);
                        }
                        break;
                    default:
                        Header length = httpResponse.getHeaders("Content-Length")[0];
                        InputStream inputStream = httpResponse.getEntity().getContent();
                        response.setContent(inputStream, Integer.valueOf(length.getValue()));
                        break;
                }
            }else{
                response.setErrcode(String.valueOf(httpResponse.getStatusLine().getStatusCode()));
                response.setErrmsg("请求失败");
            }
        } catch (IOException e) {
            LOG.error("IO流异常", e);
        } catch (Exception e) {
            LOG.error("其他异常", e);
        }

        return response;
    }
1187465
protected static function cgi_media_uri($access_token, $media_id)
    {
        $param = [
            'access_token' => $access_token,
            'media_id' => $media_id,
        ];

        return self::CGI_MEDIA_GET_URI . http_build_query($param);
    }
863693
def download(self, resource_id):
        
        self.resource_id(str(resource_id))
        self._request_uri = '{}/download'.format(self._request_uri)
1146381
def file_upload(self, folder_id: str, file_name: str, mine_type: str) -> bool:
        
        service = self.__get_service()
        media_body = MediaFileUpload(file_name, mimetype=mine_type, resumable=True)
        body = {
            'name': os.path.split(file_name)[-1],
            'mimeType': "text/csv",
            'parents': [folder_id],
        }
        return service.files().create(body=body, media_body=media_body).execute()
430845
public function delForeverMedia($media_id){
        if (!$this->access_token && !$this->checkAuth()) return false;
        $data = array('media_id' => $media_id);
        $result = $this->http_post(self::API_URL_PREFIX.self::MEDIA_FOREVER_DEL_URL.'access_token='.$this->access_token,self::json_encode($data));
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                $this->errCode = $json['errcode'];
                $this->errMsg = $json['errmsg'];
                return false;
            }
            return true;
        }
        return false;
    }
191461
def get_file_download(self, file_id):
        
        return self._create_item_response(
            self.data_service.get_file_url(file_id),
            FileDownload
        )