【问题标题】:HttpUrlConnection Get method returns status code 405HttpUrlConnection Get 方法返回状态码 405
【发布时间】:2014-10-13 02:16:01
【问题描述】:

我正在尝试使用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 做错了什么。

【问题讨论】:

  • 第一个代码中sn -p getQuery()属于什么包?
  • 确保在connection.setDoInput(true);connection.setDoOutput(true); 之前调用connection.setRequestMethod("GET");。否则,您是在告诉 HttpURLConnection 在建立连接后执行 GET。
  • 我很确定 setDoInput(true) 会导致方法设置为 POST。
  • @PM77-1 发布getQuery()。请检查。它是一个向 url 添加参数的实用程序。
  • 我认为您需要从网址中删除?

标签: java get httpurlconnection


【解决方案1】:

connection.setDoInput(true); 强制 POST 请求。让它connection.setDoInput(false);

【讨论】:

  • 对于 JDK 1.8:connection.setDoInput(true); 不强制 POST。事实上,它没有用,因为true 是默认值(根据Javadoc)。而HttpURLConnection 的默认 Http-Method 似乎是 GET。试试这个代码:connection.setDoInput(true); System.out.print(((HttpURLConnection)connection).getRequestMethod());
【解决方案2】:

我在使用 OP 代码时遇到的问题是打开输出流...:

OutputStream os = connection.getOutputStream();

...隐式地将连接从“GET”(我最初通过 setProperties 在连接上设置)更改为“POST”,从而在端点上给出 405 错误。如果你想要一个灵活的 httpConnection 方法,它同时支持 GET 和 POST 操作,那么只打开非 GET http 调用的输出流。

【讨论】:

  • 你是绝对的英雄,我撞了一个小时才发现这个。
【解决方案3】:

按照我的说法,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());

试试看。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2015-03-10
    • 2015-04-23
    • 1970-01-01
    • 2012-12-14
    相关资源
    最近更新 更多