Nitish
Nitish

Reputation: 3155

HttpUrlConnection Get method returns status code 405

I am trying to fetch data from the server using HttpURLConnection. The request is a GET request. But, it always returns status code 405(BAD_METHOD). Below is the method I wrote:

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

While if perform the same using HttpClient, I get the desired output. Below is the same operation with 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);

I am not getting what I am doing wrong with HttpUrlConnection.

Upvotes: 5

Views: 11358

Answers (3)

Daryl W
Daryl W

Reputation: 21

The issue that I ran into with the OP's code is that opening the output stream...:

OutputStream os = connection.getOutputStream();

...implicitly changes the connection from a "GET" (which I initially set on the connection via setProperties) to a "POST", thus giving the 405 error on the end point. If you want to have a flexible httpConnection method, that supports both GET and POST operations, then only open the output stream on non-GET http calls.

Upvotes: 1

Slawa
Slawa

Reputation: 1217

connection.setDoInput(true); forces POST request. Make it connection.setDoInput(false);

Upvotes: 15

Kishan Bheemajiyani
Kishan Bheemajiyani

Reputation: 3439

Well according to me into the GET method parameters are to be send as the part of the URL so try this.

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

try it.

Upvotes: 0

Related Questions