openConnection获取响应正文如何删除循环

时间:2018-11-01 21:54:28

标签: java get httpurlconnection

我有执行GET http请求的代码,我需要将响应正文验证为正在获取JSON:

 public static HTTPResult getRequest(String url) throws IOException {
        String result = null;
        URL urltouse = new URL(url);
        HttpURLConnection httpCon = (HttpURLConnection) urltouse.openConnection();
        httpCon.setRequestMethod("GET");
        Integer responseCode = httpCon.getResponseCode();
        String responseMessage = httpCon.getResponseMessage();
        if (200 <= httpCon.getResponseCode() && httpCon.getResponseCode() <= 299) {
            BufferedReader br = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String output;
            while ((output = br.readLine()) != null) {
                sb.append(output);
            }
            result = sb.toString();
        } else {
            BufferedReader br = new BufferedReader(new InputStreamReader(httpCon.getErrorStream()));
        }

        return new HTTPResult(result,responseMessage,responseCode);
    }

我可以代替:

while ((output = br.readLine()) != null) {
                    sb.append(output);

还有别的吗?看起来循环直到JSON完成才结束。如果我的JSON很大,会发生什么?

0 个答案:

没有答案