我正在使用带有支持库版本23的compileSdk 23.
我已经使用了httplegacy库(我已将它从androidSdk / android-23 / optional / org.apache.http.legacy.jar复制到app / libs文件夹中)并且在gradle中我放了:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
为了加载该库.
在我的Connection类中,我有一个以这种方式加载DefaultHttpClient实例的方法:
private static HttpClient getClient(){
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
return httpClient;
}
但Android Studio告诉我,所有apache.http类都已弃用.
我可以使用什么来遵循最佳做法?
解决方法:
This preview removes support for the Apache HTTP client. If your app
is using this client and targets Android 2.3 (API level 9) or higher,
use the HttpURLConnection class instead. This API is more efficient
because it reduces network use through transparent compression and
response caching, and minimizes power consumption
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
另一种选择是使用网络库.我个人在我的Kotlin代码上使用Fuel(但它有Java支持),在我的Java代码上使用Http-request.两个库都在内部使用HttpURLConnection.
以下是使用Http-Request库进行连接的示例:
HttpRequest request = HttpRequest.get("http://google.com");
String body = request.body();
int code = request.code();
以下是使用Fuel库进行连接的示例:
Fuel.get("http://httpbin.org/get", params).responseString(new Handler() {
@Override
public void failure(Request request, Response response, FuelError error) {
//do something when it is failure
}
@Override
public void success(Request request, Response response, String data) {
//do something when it is successful
}
});
注意:Fuel是异步库,Http-request阻塞.
标签:android,android-6-0-marshmallow,apache-httpclient-4-x
来源: https://codeday.me/bug/20190611/1221650.html