對這文章發表回應
發表限制: 非會員 可以發表
發表者: 冷日 發表時間: 2019/5/30 14:43:39
關於DefaultHttpClient 過時的問題
今天在使用之前的一個demo的時候 在導入studio之後發現 缺少jar包 然後在導入jar包後,有些方法依然不能正常使用,後來搜索了一下,恍然大悟,原來是某些api過時導致的 ,
決絕方法也 很簡單 最簡單的方法就是 直接將studio 裡面的Api版本 修改成以前的版本 高版本是可以兼容低版本的 ,
修改build.Gradle 文件裡面的 相關引用
android {
compileSdkVersion 18
defaultConfig {
8
17
}
這樣就可以輕鬆搞定了
當然這部是最終決絕的辦法 我們要瞭解 新的知識 ,
下面是從網絡上轉載的一遍介紹的比較詳細的文章 供大家學習吧
原文地址: http://www.yeetrack.com/?p=760
最近在使用Apache的httpclient的時候,maven引用了最新版本4.3,發現Idea提示DefaultHttpClient等常用的類已經不推薦使用了,之前在使用4.2.3版本的時候,還沒有被deprecated。去看了下官方文檔,確實不推薦使用了, 點擊此處詳情。
- DefaultHttpClient —> CloseableHttpClient
- HttpResponse —> CloseableHttpResponse
官方給出了新api的樣例,如下。
Get方法:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST either fully consume the response content or abort request
// execution by calling CloseableHttpResponse#close().
//建立的http連接,仍舊被response1保持著,允許我們從網絡socket中獲取返回的數據
//為了釋放資源,我們必須手動消耗掉response1或者取消連接(使用CloseableHttpResponse類的close方法)
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
response1.close();
}
Post方法:
HttpPost httpPost = new HttpPost("http://targethost/login");
//拼接參數
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
//消耗掉response
EntityUtils.consume(entity2);
} finally {
response2.close();
}
再往下看HttpClients的源碼,具體的實現都在 HttpClientBuilder
的 build
方法中,有興趣的可以去apache看源碼。
/**
* Creates {@link CloseableHttpClient} instance with default
* configuration.
*/
public static CloseableHttpClient createDefault() {
return HttpClientBuilder.create().build();
}
原文出處: 关于DefaultHttpClient 过时的问题 - q9104422999的博客 - CSDN博客