如何在Android 9 Api 28中使用HttpsUrlConnection写入远程服务器上的.txt文件

时间:2019-02-12 20:36:13

标签: android

Android开发者网站上的以下

代码示例显示了如何使用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修复它。 / p>

// 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;
}

1 个答案:

答案 0 :(得分:1)

从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>