0

I have a weird issue when using HttpURLConnection on android it gives me a status code 501 but when I try the request on curl, it gives me status code 200.

curl -X GET \
-H "Accept-Charset: UTF-8" \
https://domain.com/v1/resource?token=token12345

This is my HttpURLConnection GET request snippet

public MyResponse get(String params) {
    HttpURLConnection connection = null;
    InputStreamReader inputStream = null;
    BufferedReader reader = null;
    MyResponse response = null;

    String tokenParam = "?token=" + params;

    try {
        URL url = new URL(BASE_URL + API_VER + mResource + tokenParam);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(Method.GET);
        connection.setRequestProperty(Header.ACCEPT_CHARSET, Value.UTF_8);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

        int statusCode = connection.getResponseCode(); // code 501

        inputStream = new InputStreamReader(connection.getInputStream());
        reader = new BufferedReader(inputStream);
        StringBuilder message = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            message.append(line);
        }

        response = new MyResponse();
        response.setMessageBody(message.toString());
        response.setStatusCode(statusCode);
        if (statusCode == HTTP_OK || statusCode == HTTP_CREATED) {
            response.setSuccess(true);
        } else {
            response.setSuccess(false);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) connection.disconnect();
        try {
            if (inputStream != null) inputStream.close();
            if (reader != null) reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return response;
}

Am I missing anything?

chip
  • 1,779
  • 1
  • 22
  • 34
  • Should you instantiate a _HttpsUrlConnection_ ? – harism Jan 16 '15 at 09:41
  • You already instatiate it `connection = (HttpURLConnection) url.openConnection();` a 501 error is "not implemented" on the server side. Missed the bit about the curl, will have another look at the code sorry. – Chris Handy Jan 16 '15 at 11:21
  • How set on using HttpUrlConnection? I have some HttpGet code you can have if you want which uses the org.apache classes – Chris Handy Jan 16 '15 at 11:28
  • @ChrisHandy i'm open to other approaches. if that is working for you, i would like to give it a try – chip Jan 16 '15 at 11:39
  • You should stay with `HttpURLConnection` on Android. I don't know where the problem in your code is, but have a look at this [Github Gist](https://gist.github.com/hgoebl/af5b54f76bace9d50f43) which uses [DavidWebb](http://hgoebl.github.io/DavidWebb/), a small wrapper around HttpUrlConnection. There you can find links to alternative libraries. – hgoebl Jan 16 '15 at 11:42
  • Maybe not so important (and sure not the cause of your problem), but you're swallowing linefeeds in your `while` loop. – hgoebl Jan 16 '15 at 11:46

2 Answers2

1

setDoOutput(true) is used for POST and PUT requests for sending (output) a request body. Usually we don't need this for GET requests. Found it here

Community
  • 1
  • 1
chip
  • 1,779
  • 1
  • 22
  • 34
0

Ignore the timeout stuff if you don't need it. The method at the bottom just takes an input stream and converts it into a response for you. Hope it helps.

public boolean genLogon(){
    HttpGet m_httpGet = null;
    HttpResponse m_httpResponse = null;

    // setup timeout params for the socket and the time to connect
    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = CONNECTION_TIMEOUT;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    int timeoutSocket = DATA_TIMEOUT;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    // Create a http client with the parameters
    HttpClient m_httpClient = new DefaultHttpClient(httpParameters);

    String result = null;

    try {


        // Create a get object
        m_httpGet = new HttpGet("https://domain.com/v1/resource?token=token12345");
        m_httpGet.setHeader(Accept-Charset, "UTF-8");

        m_httpResponse = m_httpClient.execute(m_httpGet);
        HttpEntity entity = m_httpResponse.getEntity();

        if (entity != null) {

            // Get the input stream and read it out into response
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
        }

    } catch (ConnectTimeoutException cte) {
        // Toast.makeText(MainApplication.m_context, "Connection Timeout", Toast.LENGTH_SHORT).show();
        return false;
    } catch (Exception e) {
        return false;
    } finally {
        m_httpClient.getConnectionManager().closeExpiredConnections();
    }

    // See if we have a response
    if (m_httpResponse == null) {
        return false;
    }

    // check status
    if (m_httpResponse.getStatusLine() == null) {
        return false;
    }

    // If the status code is okay (200)
    if (m_httpResponse.getStatusLine().getStatusCode() == 200) {

        //Handle the repsonse
        return true

    } else {
        // response code not 200
    }

    return false;
}

private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine() method. We iterate until the
     * BufferedReader return null which means there's no more data to read. Each line will appended to a
     * StringBuilder and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
Chris Handy
  • 366
  • 1
  • 5