安卓hive教程中的java JSONParser,DefaultHttpClient中的NoSuchMethodError
我遵循this教程,并得到以下错误:
Caused by: java.lang.NoSuchMethodError: No virtual method execute(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/client/methods/CloseableHttpResponse; in class Lorg/apache/http/impl/client/DefaultHttpClient; or its super classes (declaration of 'org.apache.http.impl.client.DefaultHttpClient' appears in /system/framework/ext.jar)
at info.安卓hive.materialtabs.adpater.JSONParser.makeHttpRequest(JSONParser.java:52)
at info.安卓hive.materialtabs.UserFunctions.loginUser(UserFunctions.java:37)
at info.安卓hive.materialtabs.activity.MainActivity$Login.doInBackground(MainActivity.java:551)
at info.安卓hive.materialtabs.activity.MainActivity$Login.doInBackground(MainActivity.java:519)
下面是我正在使用的JSONParser类:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
# 1 楼答案
DefaultHttpClient在api级别22中被弃用,在api级别23中被删除
该文档甚至已从Android文档中删除,以下是指向该文档之前所在位置的链接,您可以看到它重新指向的位置: http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html
报价以防重新指导变更:
我创建了您正在使用的JSONParser类的更新版本,如下所示:
Post的异步任务示例:
Get的异步任务示例:
有关更多详细信息,请参阅我关于此代码的博客帖子:http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html