我有一个应用,为了下载Json
数据使用org.apache.http
这是我用来发出请求的类:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
@SuppressWarnings("deprecation")
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* @url - url to make request
* @method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* @url - url to make request
* @method - http request method
* @params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity,HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
问题是来自org.apache.http
的每个导入都已弃用,我不知道使用此类是否会出现问题。有人能指出我正确的方向,以便使用非弃用方法“更新”我的课程吗?
修改 来自Android M文档:
此预览删除了对Apache HTTP客户端的支持。如果您的应用使用此客户端并定位到Android 2.3(API级别9)或更高版本,请改用HttpURLConnection类。此API更高效,因为它通过透明压缩和响应缓存减少了网络使用,并最大限度地降低了功耗。要继续使用Apache HTTP API,必须首先在build.gradle文件中声明以下编译时依赖项:
android {
useLibrary 'org.apache.http.legacy'
}
所以我的应用程序会崩溃使用该类吗?
答案 0 :(得分:1)
而不是DefaultHttpClient使用
HttpClient httpClient = HttpClientBuilder.create().build();
而不是HTTP.UTF_8使用
StandardCharsets.UTF_8
答案 1 :(得分:0)
您可以转到there并查找弃用的评论,这些评论将为您提供使用方法
答案 2 :(得分:0)
对于HTTP.UTF_8,替代方案是Consts.UTF_8。他们在文档中没有提到它,这很奇怪。 Consts.UTF_8是字符集,而HTTP.UTF_8是字符串。 HttpProtocolParams.setContentCharset(HttpParams httpParams,String charset)期待一个String,而不是Consts Charset。
对于字符串,我们可以使用String.valueOf(Consts.UTF_8)