HttpUrlConnection Get方法返回状态代码405

时间:2014-10-13 02:16:01

标签: java get httpurlconnection

我正在尝试使用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的错误。

4 个答案:

答案 0 :(得分:14)

connection.setDoInput(true);强制POST请求。设为connection.setDoInput(false);

答案 1 :(得分: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());

试一试。

答案 2 :(得分:0)

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

OutputStream os = connection.getOutputStream();

...将连接从“ GET”(我最初通过setProperties在连接上初始设置)隐式更改为“ POST”,从而在端点上出现405错误。如果要具有同时支持GET和POST操作的灵活的httpConnection方法,则仅在非GET http调用上打开输出流。

答案 3 :(得分:-1)

正如您所说,状态代码405表示BAD_METHOD,因此服务器请求可能 GET 方法。尝试connection.setRequestMethod(&#34; POST&#34;);