最近很多小伙伴都在问android-URLConnection和setUseCaches(true)这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展Android9.0/P版本推荐
最近很多小伙伴都在问android-URLConnection和setUseCaches(true)这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展Android 9.0/P 版本推荐使用 HttpURLConnection、Android HttpURLConnection、Android HTTPUrlConnection POST、Android HttpURLConnection.getResponseCode()错误解决方法等相关知识,下面开始了哦!
本文目录一览:- android-URLConnection和setUseCaches(true)
- Android 9.0/P 版本推荐使用 HttpURLConnection
- Android HttpURLConnection
- Android HTTPUrlConnection POST
- Android HttpURLConnection.getResponseCode()错误解决方法
android-URLConnection和setUseCaches(true)
我正在使用当前代码在线程中下载图像:
Log.d(TAG, "Fetching image: " + BASE_URL + mURL);
URLConnection connection;
InputStream input;
connection = (new URL(BASE_URL + mURL)).openConnection();
connection.setUseCaches(true);
connection.connect();
input = connection.getInputStream();
Bitmap image = BitmapFactory.decodeStream(input);
如果setUseCaches()方法将缓存数据,则Android documentation不太清楚.从测试来看,它看起来并非如此,但是我想知道我是否做错了什么,如果有人知道setUseCaches()是否做任何事情.
解决方法:
据我所知,使用setUseCaches(true)无效,也不缓存任何内容.在Android上缓存文件的推荐方法是将文件写入私有内部存储并使用getCacheDir()方法:
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
Android 9.0/P 版本推荐使用 HttpURLConnection
早在几年前,谷歌就推荐在 Android2.3 版本以上使用 HttpURLConnection,而在即将正式发布的 Android P 版本中,谷歌彻底取消了对 Apache HTTPClient 的支持,针对此更改,开发者该如何正确适配 Android P ?
一、背景
1. 参考谷歌提供的 Android P 版本变更说明文档:
https://developer.android.com/preview/behavior-changes#apache-nonp
https://developer.android.com/preview/behavior-changes#apache-p
2.Android 6.0 版本已移除对 Apache HTTP 客户端的支持
https://developer.android.com/about/versions/marshmallow/android-6.0-changes
Android 6.0 版本移除了对 Apache HTTP 客户端的支持。如果您的应用使用该客户端,并以 Android 2.3(API 级别为 9)或更高版本为目标平台,请改用 HttpURLConnection 类。此 API 效率更高,能够通过透明压缩和响应缓存减少网络使用,并可最大限度降低耗电量。要继续使用 Apache HTTP API,须先在 build.gradle 文件中声明以下编译时依赖项:
android {
useLibrary ''org.apache.http.legacy''
}
3.P 版本修改
Remove org.apache.http.legacy from bootclasspath
从 Android P 开始,org.apache.http.legacy 库将从 bootclasspath 中删除。
(1). 修改对 TargetSdkVersion<P 的应用的影响
该修改对大多数 TargetSdkVersion<P 的应用都无影响,但是如果应用使用了系统 ClassLoader 加载 org.apache.http.* 中的类时,将在 Android P 上发生 NoClassDefFoundError 失败,因为系统 ClassLoader 不再知道这些类。为了防止将来出现类似的问题,应用应该通过应用 ClassLoader 加载类,而不是直接访问系统 ClassLoader。
(2). 修改对 TargetSdkVersion>=P 的应用的影响
对所有 TargetSdkVersion>=P 的应用,如果还是按照以前一样通过在 build.gradle 文件中声明以下编译时依赖项:\
android {
useLibrary ''org.apache.http.legacy''
}
想继续使用 Apache-http 接口,都会出现 Apache-http 接口找不到的异常:

二、适配指导
1. 继续使用 Apache-http
(1). TargetSdkVersion<P 的应用适配指导
方案一:不要使用非标准的 ClassLoader 。
方案二:应用可以自己添加依赖的 apache jar 包到工程 libs 目录规避该兼容性问题。


注意:对于最低 SDK 为 23 或更低的应用程序,android:required=“false” 属性是必需的,因为在 API 等级低于 24 的设备上,org.apache.http.legacy 库不可用。(在这些设备上,Apache HTTP 类在 bootclasspath 上可用。)
(2). TargetSdkVersion>=P 的应用适配指导
对于 TargetSdkVersion>=P 的应用如果想继续使用 Apache-http 客户端,需要在应用的 AndroidManifest.xml 文件中添加:
<uses-libraryandroid:name="org.apache.http.legacy"android:required="false"/>
2. 不再使用 Apache-http 客户端
使用 HttpURLConnection 替代 Apache-http。
Android HttpURLConnection
谷歌推荐用HttpUrlConnection
HttpURLConnection默认使用GET方式 :
URL url = new URL("www.baidu.com");
//使用HttpURLConnection打开连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//得到读取的内容(流)
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
// 为输出创建BufferedReader
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
//使用循环来读取获得的数据
while (((inputLine = buffer.readLine()) != null)){
//我们在每一行后面加上一个"\n"来换行
resultData += inputLine + "\n";
}
//关闭InputStreamReader
in.close();
//关闭http连接
urlConn.disconnect();
使用POST方式,则需要setRequestMethod设置 :
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
//获得的数据
String resultData = "";
URL url = null;
try {
//构造一个URL对象
url = new URL(httpUrl);
}
catch (MalformedURLException e){
Log.e(DEBUG_TAG, "MalformedURLException");
}
if (url != null){
try{
// 使用HttpURLConnection打开连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//因为这个是post请求,设立需要设置为true
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
// 设置以POST方式
urlConn.setRequestMethod("POST");
// Post 请求不能使用缓存
urlConn.setUseCaches(false);
urlConn.setInstanceFollowRedirects(true);
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
urlConn.connect();
//DataOutputStream流
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
//要上传的参数
String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");
//将要上传的内容写入流中
out.writeBytes(content);
//刷新、关闭
out.flush();
out.close();
//返回响应结果
BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getinputstream()))
string line = br.readline();
while(line != null){
system.out.printli(line);
line = br.readline();
}
Android HTTPUrlConnection POST
我正在使用HttpURLConnection通过POST将数据发送到服务器.我设置头,然后获取输出流并写入5个字节的数据(“ M = 005”),然后关闭输出流.
在服务器上,我收到了所有标头,正确的内容长度,但是随后得到的长度为零,并且服务器挂在readLine上.
似乎发生的事情是客户端关闭实际上从未发生,因此不会写入整个数据,因此服务器永远不会获得它.
我已经阅读了许多示例,并尝试了各种更改,以查看我是否可以以任何方式实现此目标,而效果均不理想.例如,关闭保持活动状态,然后在数据末尾强制执行CRLF(这会迫使我的数据在服务器端发出,但连接仍无法关闭.(仅用于测试),尝试使用打印写程序.
由于很多示例都在执行我的操作,因此我认为这很简单,但是我看不到它.任何帮助,将不胜感激.
StringBuilder postDataBuilder.append("M=").append(URLEncoder.encode("005", UTF8));
byte[] postData = null;
postData = postDataBuilder.toString().getBytes();
url = new URL("http://" + serverAddress + ":" + String.valueOf(serverPort));
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
conn.setUseCaches(false);
OutputStream out = conn.getoutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
// After executing the above line the server starts to successfully readLines
// until it gets to the post data when the server hangs. If I restart the
// client side then the data finally gets through but the connection on the
// server side never ends.
解决方法:
哎呀我们服务器端的错误是执行readLine而不是字符读取.由于没有CRLF,它将挂起.
Android HttpURLConnection.getResponseCode()错误解决方法
导语:个人对网络连接接触的不多,在使用时自己发现一些问题,记录一下。正文:我在使用HttpURLConnection.getResponseCode()的时候直接报错是IOException错误,responseCode = -1。一直想不明白,同一个程序我调用了两次,结果有一个链接一直OK,另一个却一直报这个错误。后来发现两个链接的区别,有一个返回的内容是空的,所以导致了这个错误。
解决方法:
方法1、网页返回内容不能是空;
方法2、不要用这个接口咯。
我们今天的关于android-URLConnection和setUseCaches(true)的分享就到这里,谢谢您的阅读,如果想了解更多关于Android 9.0/P 版本推荐使用 HttpURLConnection、Android HttpURLConnection、Android HTTPUrlConnection POST、Android HttpURLConnection.getResponseCode()错误解决方法的相关信息,可以在本站进行搜索。
本文标签: