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

HttpURLConnection GET request on Android gives weird 501 code

我在 android 上使用 HttpURLConnection 时遇到一个奇怪的问题,它给了我一个状态代码 501,但是当我在 curl 上尝试请求时,它给了我状态代码 200。

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

这是我的HttpURLConnectionGET请求片段

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

我错过了什么吗?

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

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

setDoOutput(true)用于POST和PUT请求发送(输出)请求体。通常我们不需要 GET 请求。找到了 here