线程“main”java.io.IOException中出现异常:服务器返回HTTP响应代码:URL的405

问题描述 投票:0回答:1

我使用 (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

当我在浏览器中调用该网址时,我得到了答案

java httpurlconnection
1个回答
0
投票

除非我遗漏了什么,否则你在这里不需要

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
此处。

© www.soinside.com 2019 - 2024. All rights reserved.