HttpUrlConnection Get方法返回状态代码405

问题描述 投票:5回答:4

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

java get httpurlconnection
4个回答
14
投票

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


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());

试试吧。


0
投票

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

OutputStream os = connection.getOutputStream();

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


-1
投票

如上所述,状态代码405表示BAD_METHOD,因此服务器请求可能不是GET方法。尝试connection.setRequestMethod(“POST”);

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