HttpUrlConnection的Get方法返回状态码405

5

我正在尝试使用 HttpURLConnection 从服务器获取数据。请求是一个 GET 请求。但是,它总是返回状态码 405(BAD_METHOD)。以下是我编写的方法:

URL url2 = new URL("http://www.example.com/api/client_list?");
HttpURLConnection connection = (HttpURLConnection) url2
                .openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(NET_READ_TIMEOUT_MILLIS);
connection.setConnectTimeout(CONNECTION_TIMEOUT_MILLIS);
connection.setRequestProperty("Authorization", token);
connection.setDoInput(true);
connection.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("client_id", clientRole));

OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
connection.connect();

getQuery()

private String getQuery(List<NameValuePair> params)
            throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params) {
        if (first)
            first = false;
        else
            result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

如果使用HttpClient执行相同操作,则可以获得所需的输出。以下是使用HttpClient执行相同操作:

String url = "http://www.example.com/api/client_list?client_id=" + rolename;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization", "Bearer " + token);
httpClient.execute(httpGet);

我不明白我在使用HttpUrlConnection时哪里做错了。

@PM77-1 发布了 getQuery()。请检查一下。这是一个用于向 URL 添加参数的实用工具。 - Nitish
我认为你需要从URL中删除? - Mzf
@MikeLaren 已经更正了。现在它返回 BAD_REQUEST(400) - Nitish
BAD_REQUEST(400)表示服务器接受了连接并读取了请求,但无法处理它,可能是由于某些内容缺失。您应该检查服务器日志以找出缺少了什么,但我怀疑请求字符串没有所有必需的参数,这就是为什么服务器拒绝它的原因。尝试使用诸如Wireshark、Fiddler或Charles Proxy之类的工具来比较每个请求的网络流量,看看是否能发现差异。还要检查标题,例如Content-Type和Content-Disposition。 - Mike Laren
@Krishna 这会对我有什么帮助?只有在我的状态为“HTTP_OK”时,我才会读取数据流。 - Nitish
显示剩余8条评论
3个回答

15

connection.setDoInput(true); 强制使用POST请求。将其更改为 connection.setDoInput(false);


关于JDK 1.8:connection.setDoInput(true); 不会强制使用POST。实际上,它是无用的,因为根据Javadoc,true是默认值。而且HttpURLConnection的默认Http-Method似乎是GET。请尝试使用以下代码:connection.setDoInput(true); System.out.print(((HttpURLConnection)connection).getRequestMethod()); - Würgspaß

1
我遇到的问题是,使用OP的代码时打开输出流会隐式地将连接从“GET”(我最初通过setProperties在连接上设置)更改为“POST”,因此在端点上出现405错误。如果你想要一个灵活的httpConnection方法,支持GET和POST操作,则只需在非GET http调用上打开输出流即可。

你真是个绝对的英雄,我找了一个小时才找到这个。 - Igor Flakiewicz

0

根据我的理解,在GET方法中,参数应该作为URL的一部分发送,因此可以尝试这样做。

String request = "http://example.com/index.php?param1=a&param2=b&param3=c";
URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("GET"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);



 BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());

试一下。


setRequestMethod("GET"); ===>>> 找不到符号 - MrSalesi
你使用哪个URL连接?@MrSalesi - Kishan Bheemajiyani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接