连接到 Microsoft Azure 媒体服务时如何使用网络代理

Posted

技术标签:

【中文标题】连接到 Microsoft Azure 媒体服务时如何使用网络代理【英文标题】:How to use network proxy when connecting to Microsoft Azure Media Services 【发布时间】:2016-09-09 13:10:45 【问题描述】:

当我在本地运行使用 Java 编写的 Microsoft Azure 媒体服务代码时,它可以工作,但是当我在开发环境中部署相同的代码时,我无法访问 Azure 及其抛出的 java.net.HostNotFoundException。

使用网络代理连接到 Azure 的最佳方法是什么

下面是我通过 java 和 azure-java-sdk 使用的代码

import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.util.EnumSet;

import com.microsoft.windowsazure.Configuration;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.services.media.MediaConfiguration;
import com.microsoft.windowsazure.services.media.MediaContract;
import com.microsoft.windowsazure.services.media.MediaService;
import com.microsoft.windowsazure.services.media.WritableBlobContainerContract;
import com.microsoft.windowsazure.services.media.models.AccessPolicy;
import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo;
import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission;
import com.microsoft.windowsazure.services.media.models.Asset;
import com.microsoft.windowsazure.services.media.models.AssetFile;
import com.microsoft.windowsazure.services.media.models.AssetFileInfo;
import com.microsoft.windowsazure.services.media.models.AssetInfo;
import com.microsoft.windowsazure.services.media.models.Job;
import com.microsoft.windowsazure.services.media.models.JobInfo;
import com.microsoft.windowsazure.services.media.models.JobState;
import com.microsoft.windowsazure.services.media.models.ListResult;
import com.microsoft.windowsazure.services.media.models.Locator;
import com.microsoft.windowsazure.services.media.models.LocatorInfo;
import com.microsoft.windowsazure.services.media.models.LocatorType;
import com.microsoft.windowsazure.services.media.models.MediaProcessor;
import com.microsoft.windowsazure.services.media.models.MediaProcessorInfo;
import com.microsoft.windowsazure.services.media.models.Task;


public class HelloMediaServices

    // Media Services account credentials configuration
    private static String mediaServiceUri = "https://media.windows.net/API/";
    private static String oAuthUri = "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13";
    private static String clientId = "account name";
    private static String clientSecret = "account key";
    private static String scope = "urn:WindowsAzureMediaServices";
    private static MediaContract mediaService;

    // Encoder configuration
    private static String preferedEncoder = "Media Encoder Standard";
    private static String encodingPreset = "H264 Multiple Bitrate 720p";

    public static void main(String[] args)
    

        try 
            // Set up the MediaContract object to call into the Media Services account
            Configuration configuration = MediaConfiguration.configureWithOAuthAuthentication(
            mediaServiceUri, oAuthUri, clientId, clientSecret, scope);
            mediaService = MediaService.create(configuration);


            // Upload a local file to an Asset
            AssetInfo uploadAsset = uploadFileAndCreateAsset("BigBuckBunny.mp4");
            System.out.println("Uploaded Asset Id: " + uploadAsset.getId());


            // Transform the Asset
            AssetInfo encodedAsset = encode(uploadAsset);
            System.out.println("Encoded Asset Id: " + encodedAsset.getId());

            // Create the Streaming Origin Locator
            String url = getStreamingOriginLocator(encodedAsset);

            System.out.println("Origin Locator URL: " + url);
            System.out.println("Sample completed!");

         catch (ServiceException se) 
            System.out.println("ServiceException encountered.");
            System.out.println(se.toString());
         catch (Exception e) 
            System.out.println("Exception encountered.");
            System.out.println(e.toString());
        

    

    private static AssetInfo uploadFileAndCreateAsset(String fileName)
        throws ServiceException, FileNotFoundException, NoSuchAlgorithmException 

        WritableBlobContainerContract uploader;
        AssetInfo resultAsset;
        AccessPolicyInfo uploadAccessPolicy;
        LocatorInfo uploadLocator = null;

        // Create an Asset
        resultAsset = mediaService.create(Asset.create().setName(fileName).setAlternateId("altId"));
        System.out.println("Created Asset " + fileName);

        // Create an AccessPolicy that provides Write access for 15 minutes
        uploadAccessPolicy = mediaService
            .create(AccessPolicy.create("uploadAccessPolicy", 15.0, EnumSet.of(AccessPolicyPermission.WRITE)));

        // Create a Locator using the AccessPolicy and Asset
        uploadLocator = mediaService
            .create(Locator.create(uploadAccessPolicy.getId(), resultAsset.getId(), LocatorType.SAS));

        // Create the Blob Writer using the Locator
        uploader = mediaService.createBlobWriter(uploadLocator);

        File file = new File("BigBuckBunny.mp4"); 

        // The local file that will be uploaded to your Media Services account
        InputStream input = new FileInputStream(file);

        System.out.println("Uploading " + fileName);

        // Upload the local file to the asset
        uploader.createBlockBlob(fileName, input);

        // Inform Media Services about the uploaded files
        mediaService.action(AssetFile.createFileInfos(resultAsset.getId()));
        System.out.println("Uploaded Asset File " + fileName);

        mediaService.delete(Locator.delete(uploadLocator.getId()));
        mediaService.delete(AccessPolicy.delete(uploadAccessPolicy.getId()));

        return resultAsset;
    

    // Create a Job that contains a Task to transform the Asset
    private static AssetInfo encode(AssetInfo assetToEncode)
        throws ServiceException, InterruptedException 

        // Retrieve the list of Media Processors that match the name
        ListResult<MediaProcessorInfo> mediaProcessors = mediaService
                        .list(MediaProcessor.list().set("$filter", String.format("Name eq '%s'", preferedEncoder)));

        // Use the latest version of the Media Processor
        MediaProcessorInfo mediaProcessor = null;
        for (MediaProcessorInfo info : mediaProcessors) 
            if (null == mediaProcessor || info.getVersion().compareTo(mediaProcessor.getVersion()) > 0) 
                mediaProcessor = info;
            
        

        System.out.println("Using Media Processor: " + mediaProcessor.getName() + " " + mediaProcessor.getVersion());

        // Create a task with the specified Media Processor
        String outputAssetName = String.format("%s as %s", assetToEncode.getName(), encodingPreset);
        String taskXml = "<taskBody><inputAsset>JobInputAsset(0)</inputAsset>"
                + "<outputAsset assetCreationOptions=\"0\"" // AssetCreationOptions.None
                + " assetName=\"" + outputAssetName + "\">JobOutputAsset(0)</outputAsset></taskBody>";

        Task.CreateBatchOperation task = Task.create(mediaProcessor.getId(), taskXml)
                .setConfiguration(encodingPreset).setName("Encoding");

        // Create the Job; this automatically schedules and runs it.
        Job.Creator jobCreator = Job.create()
                .setName(String.format("Encoding %s to %s", assetToEncode.getName(), encodingPreset))
                .addInputMediaAsset(assetToEncode.getId()).setPriority(2).addTaskCreator(task);
        JobInfo job = mediaService.create(jobCreator);

        String jobId = job.getId();
        System.out.println("Created Job with Id: " + jobId);

        // Check to see if the Job has completed
        checkJobStatus(jobId);
        // Done with the Job

        // Retrieve the output Asset
        ListResult<AssetInfo> outputAssets = mediaService.list(Asset.list(job.getOutputAssetsLink()));
        return outputAssets.get(0);
    


    public static String getStreamingOriginLocator(AssetInfo asset) throws ServiceException 
        // Get the .ISM AssetFile
        ListResult<AssetFileInfo> assetFiles = mediaService.list(AssetFile.list(asset.getAssetFilesLink()));
        AssetFileInfo streamingAssetFile = null;
        for (AssetFileInfo file : assetFiles) 
            if (file.getName().toLowerCase().endsWith(".ism")) 
                streamingAssetFile = file;
                break;
            
        

        AccessPolicyInfo originAccessPolicy;
        LocatorInfo originLocator = null;

        // Create a 30-day readonly AccessPolicy
        double durationInMinutes = 60 * 24 * 30;
        originAccessPolicy = mediaService.create(
                AccessPolicy.create("Streaming policy", durationInMinutes, EnumSet.of(AccessPolicyPermission.READ)));

        // Create a Locator using the AccessPolicy and Asset
        originLocator = mediaService
                .create(Locator.create(originAccessPolicy.getId(), asset.getId(), LocatorType.OnDemandOrigin));

        // Create a Smooth Streaming base URL
        return originLocator.getPath() + streamingAssetFile.getName() + "/manifest";
    

    private static void checkJobStatus(String jobId) throws InterruptedException, ServiceException 
        boolean done = false;
        JobState jobState = null;
        while (!done) 
            // Sleep for 5 seconds
            Thread.sleep(5000);

            // Query the updated Job state
            jobState = mediaService.get(Job.get(jobId)).getState();
            System.out.println("Job state: " + jobState);

            if (jobState == JobState.Finished || jobState == JobState.Canceled || jobState == JobState.Error) 
                done = true;
            
        
    


【问题讨论】:

请分享您的代码。我们不知道您是直接使用 REST API 还是使用一些 SDK。 @GauravMantri 添加了java代码 【参考方案1】:

我验证了以下通过提琴手代理工作的代码。感谢how to Capture https with fiddler, in java 给我提示的帖子:

System.setProperty("http.proxyHost", "127.0.0.1");
System.setProperty("https.proxyHost", "127.0.0.1");
System.setProperty("http.proxyPort", "8888");
System.setProperty("https.proxyPort", "8888");
System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_102\\bin\\FiddlerKeyStore");
System.setProperty("javax.net.ssl.trustStorePassword", "mypassword");

【讨论】:

我们使用的是 azure-media 0.9.4,当我执行上述操作时,出现以下错误 com.microsoft.windowsazure.exception.ServiceException: com.sun.jersey.api.client.ClientHandlerException: java .lang.RuntimeException:javax.xml.bind.MarshalException - 带有链接异常:[java.net.UnknownHostException:ams-usso-1-hos-rest-1-1.cloudapp.net] 我更新了示例以使用 System.setProperty 并验证代码正在通过提琴手工作。可能您的代理服务器在解析 ams-usso-1-hos-rest-1-1.cloudapp.net 时遇到问题。这个休息端点可用并返回响应。 ams-usso-1-hos-rest-1-1.cloudapp.net/api/… @rajadilipkolli,我怀疑java.net.UnknownHostException 问题是由您的网络环境引起的。请检查您在开发环境中的DNS设置,并检查是否可以通过IP访问某些主机,但通过域名失败。【参考方案2】:

对于像我这样面临问题的其他人,我们可以使用以下代码使用网络代理连接到 azure mediaservices

 // Set up the MediaContract object to call into the Media Services account
  Configuration configuration = MediaConfiguration.configureWithOAuthAuthentication(
                    mediaServiceUri, oAuthUri, clientId, clientSecret, scope);
  configuration.getProperties().put(Configuration.PROPERTY_HTTP_PROXY_HOST, "Hostvalue");
  configuration.getProperties().put(Configuration.PROPERTY_HTTP_PROXY_PORT, "Portvalue");
  configuration.getProperties().put(Configuration.PROPERTY_HTTP_PROXY_SCHEME, "http");
  MediaContract mediaService = MediaService.create(configuration);

现在使用 mediaService 执行其他操作。

【讨论】:

以上是关于连接到 Microsoft Azure 媒体服务时如何使用网络代理的主要内容,如果未能解决你的问题,请参考以下文章

Orchard CMS“Microsoft Azure 媒体存储”模块无法连接到新的存储帐户

无法通过 odbc 连接到 Microsoft Azure 数据库

如何使用 JetBrains DataGrip 连接到远程 Microsoft Azure 数据库

无法使用 Microsoft.EntityFrameworkCore.Cosmos 连接到 Azure Cosmos Db 帐户 - 响应状态代码

如何使用 SAS 令牌从 C# 连接到 Azure BlobStorage?

从 GCP 连接到 Azure SQL 时出现 NoClassDefFoundError com/microsoft/aad/adal4j/AuthenticationException