Java通過代理上傳檔案到Azure blob
阿新 • • 發佈:2020-08-16
最近遇到一個問題,通過Azure的Java類庫上傳檔案到Azure blob,但是客戶環境通過Proxy上網的,這就需要通過代理連線blob。
官方文件裡都沒有提及如何通過代理上傳,解決這個問題浪費了一些時間,在這裡記錄一下。
Maven引用最新版本的Azure類庫
<dependencies> <dependency> <groupId>com.azure</groupId> <artifactId>azure-storage-blob</artifactId> <version>12.8.0</version> </dependency> <dependency> <groupId>com.microsoft.azure</groupId> <artifactId>azure-storage</artifactId> <version>8.6.5</version> </dependency> <dependency>
呼叫程式碼如下:
importjava.net.Authenticator; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import com.azure.core.http.HttpClient; import com.azure.core.http.ProxyOptions; import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; import com.azure.storage.blob.BlobClient; import com.azure.storage.blob.BlobClientBuilder;public class BlobUpload { //TODO:填寫正確的代理資訊 private String ProxyAddress = ""; private int ProxyPort = 0; //TODO:填寫正確的使用者名稱和密碼 private String ProxyUserName = ""; private String ProxyPassword = ""; //TODO:填寫正確的Blob資訊 private String ConnectStr = ""; private String ContainerName = ""; private String BlobName = ""; //TODO:填寫要上傳的檔名字 private String LocalFileName = ""; public static void main(String args[]) throws Exception { try { new BlobUpload().upload(); System.out.println("上傳成功。"); } catch(Exception ex){ ex.printStackTrace(); } } private void upload() { this.getBlobClient().uploadFromFile(LocalFileName, true); } private BlobClient getBlobClient() { return new BlobClientBuilder() .connectionString(ConnectStr) .containerName(ContainerName) .blobName(BlobName) .httpClient(this.getHttpClient()) .buildClient(); } private HttpClient getHttpClient() { NettyAsyncHttpClientBuilder builder = new NettyAsyncHttpClientBuilder(); ProxyOptions proxy = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(ProxyAddress, ProxyPort)); Authenticator authenticator = new Authenticator(){ public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(ProxyUserName, ProxyPassword.toCharArray())); } }; Authenticator.setDefault(authenticator); return builder.proxy(proxy).build(); } }