java代码获取网络地址图片流

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);
    }


}

完结

这时候能获取到文件或者图片。上传自己的文件服务器啦!!!!!!撒花。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值