我使用 (java) HttpURLConnection 从远程服务器获取响应。
URL url = new URL(URL_STRING);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
当我打电话时
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
我收到这条消息:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 405 for URL: http://xxx
当我在浏览器中调用该网址时,我得到了答案
除非我遗漏了什么,否则你在这里不需要
OutputStream
。您正在执行 GET
,OutputStream
将用于 POST
或 PUT
。而且,正如我之前提到的,GET
是默认方法。
try {
URL url = new URL("https://stackoverflow.com/q/78566421/2970947");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("GET");
// connection.setDoOutput(true);
connection.getInputStream().transferTo(System.out);
} catch (Exception e) {
e.printStackTrace();
}
获取您的问题并将其打印到
System.out
此处。