关于您的编辑 2:
ImageIo.read(url),不关心 url 类型。即http或https。
您可以简单地将 url 传递给此方法,但如果您传递 https url,则需要执行某些步骤来验证 SSL 证书。请找到以下示例。
1) 对于 http 和 https:
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* @author Syed CBE
*
*/
public class Main {
public static void main(String[] args) {
int height = 0,width = 0;
String imagePath="https://www.sampledomain.com/sampleimage.jpg";
System.out.println("URL=="+imagePath);
InputStream connection;
try {
URL url = new URL(imagePath);
if(imagePath.indexOf("https://")!=-1){
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, getTrustingManager(), new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
connection = url.openStream();
}
else{
connection = url.openStream();
}
BufferedImage bufferedimage = ImageIO.read(connection);
width = bufferedimage.getWidth();
height = bufferedimage.getHeight();
System.out.println("width="+width);
System.out.println("height="+height);
} catch (MalformedURLException e) {
System.out.println("URL is not correct : " + imagePath);
} catch (IOException e) {
System.out.println("IOException Occurred : "+e);
}
catch (Exception e) {
System.out.println("Exception Occurred : "+e);
}
}
private static TrustManager[] getTrustingManager() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
return trustAllCerts;
}
}
2) 仅针对 http:
// This Code will work only for http, you can make it work for https but you need additional code to add SSL certificate using keystore
public static void getImage(String testUrl) {
String testUrl="https://sampleurl.com/image.jpg";
HttpGet httpGet = new HttpGet(testUrl);
System.out.println("HttpGet is ---->"+httpGet.getURI());
HttpResponse httpResponse = null;
HttpClient httpClient=new DefaultHttpClient();
try {
httpResponse = httpClient.execute(httpGet);
InputStream stream=httpResponse.getEntity().getContent();
BufferedImage sourceImg = ImageIO.read(stream);
System.out.println("------ source -----"+sourceImg.getHeight());
sourceImg.getWidth();
System.out.println(sourceImg);
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("------ MalformedURLException -----"+e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("------ IOEXCEPTION -----"+e);
}
}