我使用以下代码从我的网站使用android HttpURLConnection方法获取一些数据并将其放在webview textarea上。但不幸的是,获取的数据忽略了所有换行符和空行。专家能否告诉我如何在最终结果中保留空行和新行?提前感谢。
test.Data.php数据:
helloWorld1
next2
next3
输出:
helloWorld1next2next3
预期产出:
helloWorld1
next2
next3
Android代码:
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";
};
答案 0 :(得分:2)
在追加字符串时添加分隔线:
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append("\n");
}