JAVA获取网络图片一个非常奇怪的问题,java高手请进: 10
一个非常奇怪的问题,java高手请进:想获取指定url对应的图片,在百度图片中获得指定URl如:imageUrl=“http://www.chinanews.com/fi...
一个非常奇怪的问题,java高手请进:
想获取指定url对应的图片,在百度图片中获得指定URl如:imageUrl=“http://www.chinanews.com/fileftp/2010/07/2010-07-29/U225P4T47D14612F967DT20100729095825.jpg”
代码:
HttpURLConnection con = null;
URL url = new URL(imageUrl);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(10 * 1000);
con.setDoInput(true);
con.setDoOutput(true);
con.getInputStream();
此时在最后一句代码时会报出FileNotFoundException,但是我把url地址中【.com】改为【.com.cn】,也就是加上【.cn】,再执行同样的代码就没有错了,问题是两个URL都能在浏览器中直接打开图片的。 展开
想获取指定url对应的图片,在百度图片中获得指定URl如:imageUrl=“http://www.chinanews.com/fileftp/2010/07/2010-07-29/U225P4T47D14612F967DT20100729095825.jpg”
代码:
HttpURLConnection con = null;
URL url = new URL(imageUrl);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(10 * 1000);
con.setDoInput(true);
con.setDoOutput(true);
con.getInputStream();
此时在最后一句代码时会报出FileNotFoundException,但是我把url地址中【.com】改为【.com.cn】,也就是加上【.cn】,再执行同样的代码就没有错了,问题是两个URL都能在浏览器中直接打开图片的。 展开
1个回答
展开全部
你确定有问题?我试了一下,加不加.cn都可以读到
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLConnection {
public static void main(String[] args) throws IOException {
final String imageUrl="http://www.chinanews.com.cn/fileftp/2010/07/2010-07-29/U225P4T47D14612F967DT20100729095825.jpg";
HttpURLConnection con = null;
URL url = new URL(imageUrl);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(10 * 1000);
con.setDoInput(true);
con.setDoOutput(true);
final InputStream in = con.getInputStream();
final byte[] buffer = new byte[1024 * 100];
int byteRead;
long totlaByteRead = 0;
while((byteRead = in.read(buffer)) > 0){
totlaByteRead += byteRead;
System.out.println(byteRead+"从URL获取字节");
}
System.out.println("总共获取字节:" + totlaByteRead);
in.close();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLConnection {
public static void main(String[] args) throws IOException {
final String imageUrl="http://www.chinanews.com.cn/fileftp/2010/07/2010-07-29/U225P4T47D14612F967DT20100729095825.jpg";
HttpURLConnection con = null;
URL url = new URL(imageUrl);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(10 * 1000);
con.setDoInput(true);
con.setDoOutput(true);
final InputStream in = con.getInputStream();
final byte[] buffer = new byte[1024 * 100];
int byteRead;
long totlaByteRead = 0;
while((byteRead = in.read(buffer)) > 0){
totlaByteRead += byteRead;
System.out.println(byteRead+"从URL获取字节");
}
System.out.println("总共获取字节:" + totlaByteRead);
in.close();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询