Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 593
Nitish Avatar asked Oct 13 '14 02:10

Nitish


2 Answers

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

like image 52
Slawa Avatar answered Sep 21 '22 17:09

Slawa


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.

like image 27
Daryl W Avatar answered Sep 21 '22 17:09

Daryl W