最近遇到一个问题,通过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>
调用代码如下:
import java.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(); } }