在传递相同的参数时,HttpURLConnection在Android 5.1和4.4上返回了不同的结果

时间:2016-08-15 05:57:06

标签: java android android-studio

public static String request(String httpUrl, String httpArg) {
    BufferedReader reader = null;
    String result = "";
    StringBuffer sbf = new StringBuffer();
    httpUrl = httpUrl + "?" + httpArg;
    try {
        URL url = new URL(httpUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("apikey", myAPpiKey);
        conn.connect();
        if (conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

上面的代码在Android 5.1和Android 6.0上运行良好,它返回了我想要的正确结果。但是当我在Android 4.4上运行这些,使用相同的参数时,它返回了不同的结果。我已经尝试了几次,并将调试器附加到进程中。我发现连接可以成功构建, ResponseCode 200 。 我想HttpURLConnection参数一定有问题,所以服务器返回了不同的结果。我是否以适用于Android 5.1和6.0但不适用于4.4的方式设置了参数?谁能告诉我我哪里做错了?

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

URL url = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setChunkedStreamingMode(0);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("apikey", myAPpiKey);
if (conn.getResponseCode() == 200) {
    InputStream is = conn.getInputStream();
    .........
}

它对我有用。希望它会奏效。