gpt4 book ai didi

java - org.apache.http 已弃用,该使用什么?

转载 作者:行者123 更新时间:2023-12-01 11:11:25 24 4
gpt4 key购买 nike

我有一个应用程序,为了下载 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'
}

所以我的应用程序会使用该类崩溃,对吗?

最佳答案

使用 DefaultHttpClient 代替

HttpClient httpClient = HttpClientBuilder.create().build();

并且使用 HTTP.UTF_8 代替

StandardCharsets.UTF_8

关于java - org.apache.http 已弃用,该使用什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32313034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com