首页 > 解决方案 > 如何修复“线程“主”java.io.IOException中的异常:服务器返回HTTP响应代码:URL 403”错误?

问题描述

我正在使用 Django 服务器并收到错误消息Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL"

 public static void main(String[] args) throws Exception {
    // check if the user enter the right args from the command line.
    if(args.length != 2){
        System.out.println("Usage: java Reverse "
        + "http://<location of your servlet/script> "
        + "string_to_reverse");// display the error.
        System.exit(1); // exit the program.
    }
    /**the sting that will be reversed may contain spaces or other
     * non-alphanumeric characters. These characters must be
     * encoded because the string is processed on its way to the server.
     * the URLEncoder class methods encode the characters.*/
    String stringToReverse = URLEncoder.encode(args[1], "UTF-8");

    // create object for the specified url for the command line.
    URL url = new URL(args[0]);
    // sets the connection so that it can write to it.
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    connection.setReadTimeout(5000);
    connection.setConnectTimeout(5000);
    // The program then creates an output stream on the connection
    // and opens an OutputSteamWriter on it;
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
    // the program writes the required information t the output
    // stream and closes the stream.
    out.write("string = " + stringToReverse);
    out.close();
    // read the specified url.
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    String decodeString;
    while((decodeString = in.readLine()) != null ){
        System.out.println(decodeString);
    }
    in.close();
}

错误:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://127.0.0.1:8000/test
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
    at Reverse.main(Reverse.java:52)

我还尝试了以下方法来修复错误,但仍然无法正常工作。

connection.setRequestProperty("http.agent", "Chrome");
connection.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
connection.setRequestProperty("User-agent", "Mozilla/5.0");
connection.setRequestProperty("User-agent", "Mozilla");

有人可以帮我解决这个问题吗?

标签: javadjangohttphttp-status-code-403http-status-codes

解决方案


推荐阅读