как исправить "Исключение в потоке" main "java .io.IOException: сервер вернул код ответа HTTP: 403 для URL" Ошибка? - PullRequest
0 голосов
/ 13 апреля 2020

Я использую 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");

Может кто-нибудь помочь мне исправить это?

...