Java –服务器返回的HTTP响应代码:URL的403

一个简单的Java程序尝试从Internet下载一些内容:

try (InputStream is = new URL(url).openStream();
       BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
      while ((line = br.readLine()) != null) {
          result.append(line);
      }
  }

但是,某些Web服务器返回以下HTTP 403错误吗?

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://mkyong.com
	at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919)
	at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)
	at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
	at java.base/java.net.URL.openStream(URL.java:1139)

要解决此问题,请在HTTP请求标头中添加一个User-Agent ,如下所示:

JavaDownloadSample.java
package com.mkyong;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class JavaDownloadSample {

    public static void main(String[] args) throws IOException {

        String result = downloadWebPage("https://mkyong.com");
        System.out.println(result);

    }

    private static String downloadWebPage(String url) throws IOException {

        StringBuilder result = new StringBuilder();
        String line;

        // add user agent 
        URLConnection urlConnection = new URL(url).openConnection();
        urlConnection.addRequestProperty("User-Agent", "Mozilla");
        urlConnection.setReadTimeout(5000);
        urlConnection.setConnectTimeout(5000);

        try (InputStream is = new URL(url).openStream();
             BufferedReader br = new BufferedReader(new InputStreamReader(is))) {

            while ((line = br.readLine()) != null) {
                result.append(line);
            }

        }

        return result.toString();

    }

}

参考文献

  • URLConnection JavaDocs
  • Java –如何从互联网下载网页?
  • 维基百科-HTTP 403

翻译自: https://mkyong.com/java/java-server-returned-http-response-code-403-for-url/

你可能感兴趣的:(java,前端,后端)