Android上的HttpURLConnection GET请求给出了奇怪的501代码

时间:2015-01-16 09:28:28

标签: java android httpurlconnection

我在Android上使用HttpURLConnection时有一个奇怪的问题,它给我一个状态代码501但是当我在curl上尝试请求时,它给我状态代码200.

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

这是我的HttpURLConnection GET请求代码段

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

我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

setDoOutput(true)用于发送(输出)请求正文的POST和PUT请求。通常我们不需要这个GET请求。找到它here

答案 1 :(得分:0)

如果您不需要,请忽略超时内容。 底部的方法只接受输入流并将其转换为响应。 希望它有所帮助。

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