首页 > 解决方案 > 如何在 Android 9 Api 28 中使用 HttpsUrlConnection 写入远程服务器上的 .txt 文件

问题描述

下面来自 Android Developers 站点的示例代码显示了如何使用 HttpsUrlConnection 从远程服务器读取 .html 站点或 .txt 文件,并且在 Android 9 Api28 中完美运行,但是没有示例如何使用 HttpsUrlConnection 写入 .txt 文件,我的代码有效通过使用 UrlConnection 在 android 5,6,7,8 api 23,25,27 中完美,在 android 9 api 28 中不起作用,我找不到任何信息如何为 android 9 Api 28 修复它。

// works perfect in android 9 api28
protected Void doInBackground(Void... params) {        
try{
URL url = new URL("https://somesite/test.txt");
res= downloadUrl(url);            
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {            
}
return null;
}
private String downloadUrl(URL url) throws IOException {
InputStream stream = null;
HttpsURLConnection  connection = null;
String result = null;
try {
connection = (HttpsURLConnection) url.openConnection();connection.setReadTimeout(3000);connection.setConnectTimeout(3000);connection.setRequestMethod("GET");connection.setDoInput(true);connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode != HttpsURLConnection.HTTP_OK) {
throw new IOException("HTTP error code: " + responseCode);
}
stream = connection.getInputStream();
if (stream != null) {
result = readStream(stream);
}
} finally {
if (stream != null) {
stream.close();
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
public String readStream(InputStream stream) throws IOException, UnsupportedEncodingException {
Reader reader = null;
int readSize;
reader = new InputStreamReader(stream, "cp1251");
char[] rawBuffer = new char[100000];
StringBuffer buffer = new StringBuffer();
while (((readSize = reader.read(rawBuffer)) != -1)) {
buffer.append(rawBuffer, 0, readSize);
}
return buffer.toString();
}
// code wich works perfect in android 5,6,7,8, but doesn't work in android 9 api 28
protected Void doInBackground(Void... params) {        
URLConnection connection;int timeout = 10000;   
URL url;
try {
url = new URL("ftp://username:password@somesite/test.txt");
connection = url.openConnection();            connection.setConnectTimeout(timeout);connection.setReadTimeout(timeout);connection.setDoInput(true);connection.setDoOutput(true);connection.connect();
BufferedWriter out=new BufferedWriter (new OutputStreamWriter(connection.getOutputStream(),"cp1251"));
out.write("some text");out.flush();out.close();
} catch (IOException e) {
}
return null;
}

标签: android

解决方案


禁止来自 Android 9 的明文流量。您将需要手动允许它添加以下代码以显示。

android:networkSecurityConfig="@xml/network_security_config"

此外,创建xml/network_security_config.xml文件并添加以下代码以允许明文流量:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

推荐阅读