【问题标题】:HttpURLConnection GET request on Android gives weird 501 codeAndroid上的HttpURLConnection GET请求给出了奇怪的501代码
【发布时间】:2015-01-16 09:28:28
【问题描述】:

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

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

这是我的HttpURLConnectionGET请求sn-p

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

我错过了什么吗?

【问题讨论】:

  • 你应该实例化一个 HttpsUrlConnection 吗?
  • 不错@harism 我会调查的
  • 您已经将其实例化connection = (HttpURLConnection) url.openConnection(); 501 错误在服务器端“未实现”。错过了有关 curl 的部分,抱歉,将再看一下代码。
  • 如何设置使用HttpUrlConnection?如果你想要使用 org.apache 类,我有一些 HttpGet 代码
  • @ChrisHandy 我对其他方法持开放态度。如果这对你有用,我想试一试

标签: java android httpurlconnection


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-02-22
      • 2011-11-27
      • 1970-01-01
      • 2017-09-17
      • 2020-05-07
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多