java.io.IOException:服务器返回HTTP响应代码:403表示URL
我想从url下载mp3文件:http://upload13.music.qzone.soso.com/30671794.mp3,我总是得到java.io.IOException:服务器返回HTTP响应代码:403 for URL。但是使用浏览器打开网址时没关系。以下是我的代码的一部分:
I want to download the mp3 file from url : "http://upload13.music.qzone.soso.com/30671794.mp3", i always got java.io.IOException: Server returned HTTP response code: 403 for URL. But it's ok when open the url using browser. Below is part of my code:
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
URL url = new URL(link);
URLConnection urlConn = url.openConnection();
urlConn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
String contentType = urlConn.getContentType();
System.out.println("contentType:" + contentType);
InputStream is = urlConn.getInputStream();
bis = new BufferedInputStream(is, 4 * 1024);
bos = new BufferedOutputStream(new FileOutputStream(
fileName.toString()));
有人可以帮助我吗?在此先感谢!
Anyone could help me? Thanks in advance!
而不是在java中使用 URLConnection
,如果你使用 HttpURLConnection
你应该可以从java访问所请求的网页。请尝试以下代码:
Instead of using URLConnection
in java, if you use HttpURLConnection
you should beable to access the requested web page from java. Try the following code:
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
普通的java使用 urlConnection
不会被接受连接网络。要访问浏览器,它需要执行搜索而不会出现 HTTP响应代码:403为URL
Normal java using urlConnection
wont be accepted to access the internet. To access the browser it will need to perform a search without theexception HTTP response code : 403 for URL
编辑(@Mordechai):无需进行投射,只需添加用户代理。
EDIT (@Mordechai): No need to do the casting, just add the user agent.