java代码获取网络地址图片流
在开发中避免不了要接收对面第三方传递过来的网络文件地址。需获取到文件流并上传到自己的文件服务器上。以下是我所需要的代码
maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
代码展示
package org.example;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
String filePath = "https://xxxxxxxxx";
InputStream is = null;
try {
if (filePath.contains("https")){
SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
NoopHostnameVerifier.INSTANCE);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(scsf).build();
HttpGet httpget = new HttpGet(filePath);
CloseableHttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}else if (filePath.contains("http")){
URL url = new URL(filePath);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.connect();
is = urlcon.getInputStream();
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(is);
System.out.println(is);
System.out.println(is);
}
}
完结
这时候能获取到文件或者图片。上传自己的文件服务器啦!!!!!!撒花。。。。