【问题标题】:How to keep newlines and empty lines when geting remote url content using HttpURLConnection?使用 HttpURLConnection 获取远程 url 内容时如何保留换行符和空行?
【发布时间】:2018-05-05 14:27:09
【问题描述】:

我正在使用以下代码使用 android HttpURLConnection 方法从我的网站获取一些数据并将其放在 webview textarea 上。但不幸的是,获取的数据忽略了所有换行符和空行。专家能否告诉我如何在最终结果中保留空行和新行?提前致谢。

test.Data.php 数据:

helloWorld1

next2
next3

输出:

helloWorld1next2next3  

预期输出:

helloWorld1

next2
next3

安卓代码:

public String sendGetRequest() {

        try {

            StrictMode.setThreadPolicy(new Builder().permitAll().build());

            HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://mywebsite.com/testData.php").openConnection();
            myURLConnection.setReadTimeout(60000);
            myURLConnection.setConnectTimeout(60000);
            myURLConnection.setRequestMethod("GET");
            myURLConnection.setUseCaches(false);
            myURLConnection.setDoInput(true);
            myURLConnection.setDoOutput(true);
            myURLConnection.setRequestProperty("Content-Type", "text");
            myURLConnection.setRequestProperty("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 6.0;");

            OutputStream os = myURLConnection.getOutputStream();

            os.close();

            myURLConnection.connect();

            BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));


            StringBuffer sb = new StringBuffer();


            String line;

            while ((line = in.readLine()) != null) {

                sb.append(line);

            }
            in.close();


            // Update your UI
            mWebView.loadUrl("javascript:Parseit('" + sb.toString() + "');");


        } catch (Exception e) {

        }
        return null;

    }

webview 上的javascript:

function Parseit(data)
{

var myTextArea = document.getElementById('area1');
myTextArea.innerHTML += data+"\n";

};

【问题讨论】:

    标签: java android newline httpurlconnection blank-line


    【解决方案1】:

    在附加字符串时添加断线:

     while ((line = in.readLine()) != null) {
    
                    sb.append(line);
                    sb.append("\n");
                }
    

    【讨论】:

    • 感谢您的回复。我已经尝试过了,但它没有用。我在其他帖子中看到使用 readline() 时会丢失换行符和空行!但我不知道如何保存它们!
    • 你使用这种方法的结果是什么?因为当您看到代码时,它会在您阅读的每一行中添加一个新的换行符。也许您的服务器响应只是一行?
    • 如果它在浏览器上键入 testData.php 的 url,示例数据按预期显示为多行(与上述预期输出相同),因此服务器响应不能是一行。即使我看testData.php的源码,数据是多行的!
    • 好的,使用这种方法的结果是什么?你能在while内打印每一行吗? Log.d("标签", 行); sb.append(line);
    • 结果使用 sb.append(line);sb.append("\n");是这样的:helloWorld1
      next2
      next3。我不得不提一下,我使用了不同的方法,将
      手动添加到我的服务器数据(testData.php)中,看看这是否有所不同,但仍然都在一行中!(如果我不把那些
      和只在不同的行上输入数据,然后当我在浏览器上输入 url 时,所有数据都显示在一行中!)。因此,无论有没有
      的服务器数据都会在 webview textarea 内的一行中生成所有数据!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 2021-05-25
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    相关资源
    最近更新 更多