java - 如何修复“线程“主”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");
有人可以帮我解决这个问题吗?
解决方案
推荐阅读
- python - Python:URL 图像下载。URL 包含重音字母。我收到一个错误
- java - Java日期时间减法
- php - 为什么本地 PHP 服务器没有发出警告,而 Web 服务器(hostgator)发出警告?
- chatbot - Microsoft 聊天机器人对话如何存储在 Azure 中?
- azure - Azure 订阅:在 PowerShell 上使用证书或 AAD 身份验证?
- python - AWS API 网关,1 个 lambda,每个端点具有公共和私有 vpc 访问权限?
- r - 如何在 R 中使用 ggplot2 构建正确的直方图?
- selenium - 是否可以使用 Selenium 对许多基于云的虚拟机实例进行负载测试?
- python - 'x' 未在自定义十进制转换函数中定义
- java - 如何执行基本的 Spring Boot 应用程序安全性