java 使用 URL 访问网络资源问题

 @Test public void test9 throws IOException { URL url = new URL"http://uploadfile.deskcity.org/2015/1020/20151020121922435.jpg"; DataInputStream dataInputStream = new DataInputStreamurl.openStream; System.out.printlndataInputStream.read; }

图片可以访问,为什么报错 403

java.io.IOException: Server returned HTTP response code: 403 for URL: http://uploadfile.deskcity.org/2015/1020/20151020121922435.jpg at sun.net.www.protocol.http.HttpURLConnection.getInputStreamUnknown Source at java.net.URL.openStreamUnknown Source at com.tuzuan.test.AllTest.test9AllTest.java:181 at sun.reflect.NativeMethodAccessorImpl.invoke0Native Method at sun.reflect.NativeMethodAccessorImpl.invokeUnknown Source at sun.reflect.DelegatingMethodAccessorImpl.invokeUnknown Source at java.lang.reflect.Method.invokeUnknown Source at org.junit.runners.model.FrameworkMethod$1.runReflectiveCallFrameworkMethod.java:50 at org.junit.internal.runners.model.ReflectiveCallable.runReflectiveCallable.java:12 at org.junit.runners.model.FrameworkMethod.invokeExplosivelyFrameworkMethod.java:47 at org.junit.internal.runners.statements.InvokeMethod.evaluateInvokeMethod.java:17 at org.junit.runners.ParentRunner.runLeafParentRunner.java:325 at org.junit.runners.BlockJUnit4ClassRunner.runChildBlockJUnit4ClassRunner.java:78 at org.junit.runners.BlockJUnit4ClassRunner.runChildBlockJUnit4ClassRunner.java:57 at org.junit.runners.ParentRunner$3.runParentRunner.java:290 at org.junit.runners.ParentRunner$1.scheduleParentRunner.java:71 at org.junit.runners.ParentRunner.runChildrenParentRunner.java:288 at org.junit.runners.ParentRunner.access$000ParentRunner.java:58 at org.junit.runners.ParentRunner$2.evaluateParentRunner.java:268 at org.junit.runners.ParentRunner.runParentRunner.java:363 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.runJUnit4TestReference.java:86 at org.eclipse.jdt.internal.junit.runner.TestExecution.runTestExecution.java:38 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTestsRemoteTestRunner.java:459 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTestsRemoteTestRunner.java:675 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runRemoteTestRunner.java:382 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.mainRemoteTestRunner.java:192

===============================================================

改了下,应该是防盗链的问题

HttpURLConnection conn = HttpURLConnection url.openConnection;
conn.setRequestMethod"GET";// 声明请求方式
conn.setConnectTimeout6 * 1000;// 设置连接超时
conn.setRequestProperty"User-Agent", "Mozilla/4.0 compatible; MSIE 7.0; Windows NT 5.1; Maxthon;";
conn.setRequestProperty"Accept-Encoding", "gzip";

报错是Unknown source.你看下你本机浏览器能否访问:http://uploadfile.deskcity.org

是否服务器禁止了java默认的useragent?

发表评论

电子邮件地址不会被公开。 必填项已用*标注