StorageException для лазурного блоба с Java

1

Когда я пытаюсь создать контейнер для своего хранилища, я получаю StorageException. 1. Я создал лазурную учетную запись. 2. Я создал azure storage для blob 3.I wrotten simple test (ниже) 4. Я сделал этот код на локальной машине и получил исключение. Что не так?

public class Test {
public static final String storageConnectionString =
        "DefaultEndpointsProtocol=https;" +
                "AccountName=my_account;" +
                "AccountKey=my_account_key";


public static void main(String[] args) throws StorageException, InvalidKeyException, URISyntaxException {



    pushControll();

}

public static void pushControll() throws URISyntaxException, StorageException, InvalidKeyException {

        CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

        CloudBlobClient blobClient = storageAccount.createCloudBlobClient();


        CloudBlobContainer container = blobClient.getContainerReference("observer");

        container.create();




    }
}

Я получаю StorageException ->:

Exception in thread "main" com.microsoft.azure.storage.StorageException: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:89)
at com.microsoft.azure.storage.core.StorageRequest.materializeException(StorageRequest.java:307)
at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:182)
at com.microsoft.azure.storage.blob.CloudBlobContainer.create(CloudBlobContainer.java:279)
at com.microsoft.azure.storage.blob.CloudBlobContainer.create(CloudBlobContainer.java:252)
at ru.marketirs.model.Test.pushControll(Test.java:40)
at ru.marketirs.model.Test.main(Test.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Процесс завершен с кодом выхода 1

Что я сделал не так?

  • 1
    Ваш код выглядит нормально для меня. Пожалуйста, проверьте на 2 вещи: 1) Убедитесь, что имя учетной записи / ключ правильный и 2) Проверьте часы на вашем компьютере и посмотрите, работает ли он медленно. Эти 2 вещи могут вызвать ошибку, которую вы получаете.
  • 0
    Большое спасибо. Ваш совет сработал. Проблема была в часах на моем компьютере.
Показать ещё 3 комментария
Теги:
azure
azure-storage-blobs

2 ответа

1
Лучший ответ

Ваш код выглядит нормально для меня. Проверьте 2 вещи: 1) Убедитесь, что имя/ключ учетной записи является правильным и 2) Проверьте часы на своем компьютере и посмотрите, работает ли он медленно. Эти две вещи могут вызвать ошибку, которую вы получаете.

1

Чтобы передать прокси-сервер, пожалуйста, используйте, как показано ниже, он работает так, как ожидалось, и он был протестирован.

public class AzureUpload {

    // Define the connection-string with your values
    /*public static final String storageConnectionString =
        "DefaultEndpointsProtocol=http;" +
        "AccountName=your_storage_account;" +
        "AccountKey=your_storage_account_key";*/
    public static final String storageConnectionString =
            "DefaultEndpointsProtocol=http;" +
            "AccountName=test2rdrhgf62;" +
            "AccountKey=1gy3lpE7Du1j5ljKiupjhgjghjcbfgTGhbntjnRfr9Yi6GUQqVMQqGxd7/YThisv/OVVLfIOv9kQ==";

    // Define the path to a local file.
    static final String filePath = "D:\\Project\\Supporting Files\\Jar's\\Azure\\azure-storage-1.2.0.jar";
    static final String file_Path = "D:\\Project\\Healthcare\\Azcopy_To_Azure\\data";

    public static void main(String[] args) {
        try
        {
            // Retrieve storage account from connection-string.
            //String storageConnectionString = RoleEnvironment.getConfigurationSettings().get("StorageConnectionString");
            //Proxy httpProxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("132.186.192.234",8080));
            System.setProperty("http.proxyHost", "102.122.15.234");
            System.setProperty("http.proxyPort", "80");
            System.setProperty("https.proxyUser", "ad001\\empid001");
            System.setProperty("https.proxyPassword", "pass!1");
            // Retrieve storage account from connection-string.
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();


            // Get a reference to a container.
            // The container name must be lower case
            CloudBlobContainer container = blobClient.getContainerReference("rpmsdatafromhospital");

            // Create the container if it does not exist.
            container.createIfNotExists();

            // Create a permissions object.
            BlobContainerPermissions containerPermissions = new BlobContainerPermissions();

            // Include public access in the permissions object.
            containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);

            // Set the permissions on the container.
            container.uploadPermissions(containerPermissions);

            // Create or overwrite the new file to blob with contents from a local file.
            /*CloudBlockBlob blob = container.getBlockBlobReference("azure-storage-1.2.0.jar");
            File source = new File(filePath);
            blob.upload(new FileInputStream(source), source.length());*/

            String envFilePath = System.getenv("AZURE_FILE_PATH");

            //upload list of files/directory to blob storage
            File folder = new File(envFilePath);
            File[] listOfFiles = folder.listFiles();

            for (int i = 0; i < listOfFiles.length; i++) {
              if (listOfFiles[i].isFile()) {
                System.out.println("File " + listOfFiles[i].getName());

                CloudBlockBlob blob = container.getBlockBlobReference(listOfFiles[i].getName());
                File source = new File(envFilePath+"\\"+listOfFiles[i].getName());
                blob.upload(new FileInputStream(source), source.length());
                System.out.println("File " + listOfFiles[i].getName()+ " upload successful");

              }
              //directory upload
              /*else if (listOfFiles[i].isDirectory()) {
                System.out.println("Directory " + listOfFiles[i].getName());

                CloudBlockBlob blob = container.getBlockBlobReference(listOfFiles[i].getName());
                File source = new File(file_Path+"\\"+listOfFiles[i].getName());
                blob.upload(new FileInputStream(source), source.length());
              }*/
            }

        }catch (Exception e)
        {
            // Output the stack trace.
            e.printStackTrace();
        }
    }
}

.Net или С#, то, пожалуйста, добавьте ниже код в "App.config"

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>

    <system.net> 
     <defaultProxy enabled="true" useDefaultCredentials="true"> 
       <proxy usesystemdefault="true" /> 
     </defaultProxy>
    </system.net>

</configuration>

Ещё вопросы

Сообщество Overcoder
Наверх
Меню