JSONParser从androidhive教程,在的NoSuchMethodError DefaultHttpClient教程、androidhive、JSONParser、NoSuchMethod

2023-09-05 02:59:20 作者:Thorn(刺)

我下面这个教程,并收到此错误:

 产生的原因:java.lang.NoSuchMethodError:无虚方法execute(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/client/methods/CloseableHtt$p$psponse;在课堂上Lorg /阿帕奇/ HTTP / IMPL /客户/ DefaultHttpClient;或者它的超类(声明org.apache.http.impl.client.DefaultHttpClient出现在/system/framework/ext.jar)
                在info.androidhive.materialtabs.adpater.JSONParser.makeHtt prequest(JSONParser.java:52)
                在info.androidhive.materialtabs.UserFunctions.loginUser(UserFunctions.java:37)
                在info.androidhive.materialtabs.activity.MainActivity $ Login.doInBackground(MainActivity.java:551)
                在info.androidhive.materialtabs.activity.MainActivity $ Login.doInBackground(MainActivity.java:519)
 

下面是我使用的JSONParser类:

 公共类JSONParser {
     静态的InputStream是= NULL;
        静态的JSONObject jObj = NULL;
        静态JSON字符串=;
        //构造
        公共JSONParser(){
        }
        //功能得到URL JSON
        //通过HTTP POST或GET方法
        公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
                名单<的NameValuePair> PARAMS){
            //使HTTP请求
            尝试 {
                //检查请求的方法
                如果(方法==POST){
                    //请求方法是POST
                    // defaultHttpClient
                    DefaultHttpClient的HttpClient =新DefaultHttpClient();
                    HttpPost httpPost =新HttpPost(URL);
                    httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));
                    HTT presponse HTT presponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = HTT presponse.getEntity();
                    是= httpEntity.getContent();
                }否则,如果(方法==GET){
                    //请求方法是GET
                    DefaultHttpClient的HttpClient =新DefaultHttpClient();
                    字符串中的paramString = URLEn codedUtils.format(PARAMS,UTF-8);
                    网址+ =? +中的paramString;
                    HTTPGET HTTPGET =新HTTPGET(URL);
                    HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                    HttpEntity httpEntity = HTT presponse.getEntity();
                    是= httpEntity.getContent();
                }
            }赶上(UnsupportedEncodingException E){
                e.printStackTrace();
            }赶上(ClientProtocolException E){
                e.printStackTrace();
            }赶上(IOException异常E){
                e.printStackTrace();
            }
            尝试 {
                的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(
                        是,ISO-8859-1),8);
                StringBuilder的SB =新的StringBuilder();
                串线= NULL;
                而((行= reader.readLine())!= NULL){
                    sb.append(行+\ N);
                }
                is.close();
                JSON = sb.toString();
            }赶上(例外五){
                Log.e(缓冲区错误,转换的结果错误+ e.toString());
            }
            //尝试解析字符串到一个JSON对象
            尝试 {
                jObj =新的JSONObject(JSON);
            }赶上(JSONException E){
                Log.e(JSON解析器,错误分析数据+ e.toString());
            }
            //返回JSON字符串
            返回jObj;
        }
}
 

解决方案

DefaultHttpClient是德precated在API级别22,而在API级别23取出。

该文件甚至从Android文档中删除,这里是链接到的文件是previously,你可以看到它重新定向到: 的http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html

报价以防万一再直接修改:

  

Android的6.0版本将删除Apache的HTTP客户端支持。如果   您的应用程序正在使用此客户端和目标的Andr​​oid 2.3(API级别9)或   更高,使用的HttpURLConnection类代替。这个API是更   高效,因为它能通过透明降低了网络使用   COM pression和响应缓存,并且将功耗降至最低。

我创造了你正在使用的JSONParser类的更新版本,那就是:

 进口android.util.Log;
进口org.json.JSONException;
进口org.json.JSONObject;
进口java.io.BufferedInputStream中;
进口java.io.BufferedReader中;
进口java.io.DataOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口java.net.HttpURLConnection中;
进口的java.net.URL;
进口java.net.URLEn codeR;
进口的java.util.HashMap;

公共类JSONParser {

    字符串charset =UTF-8;
    HttpURLConnection的康涅狄格州;
    DataOutputStream类WR;
    StringBuilder的结果;
    网址urlObj;
    JSONObject的jObj = NULL;
    StringBuilder的sbParams;
    字符串paramsString;

    公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
                                      HashMap的<字符串,字符串> PARAMS){

        sbParams =新的StringBuilder();
        INT I = 0;
        对于(字符串键:params.keySet()){
            尝试 {
                如果(ⅰ!= 0){
                    sbParams.append(与&);
                }
                sbParams.append(键).append(=)
                        .append(URLEn coder.en code(params.get(键),字符集));

            }赶上(UnsupportedEncodingException E){
                e.printStackTrace();
            }
            我++;
        }

        如果(method.equals(POST)){
            //请求方法是POST
            尝试 {
                urlObj =新的URL(网址);

                康恩=(HttpURLConnection类)urlObj.openConnection();

                conn.setDoOutput(真正的);

                conn.setRequestMethod(POST);

                conn.setRequestProperty(接收字符集,字符集);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                WR =新DataOutputStream类(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            }赶上(IOException异常E){
                e.printStackTrace();
            }
        }
        否则,如果(method.equals(GET)){
            //请求方法是GET

            如果(sbParams.length()!= 0){
                网址+ =? + sbParams.toString();
            }

            尝试 {
                urlObj =新的URL(网址);

                康恩=(HttpURLConnection类)urlObj.openConnection();

                conn.setDoOutput(假);

                conn.setRequestMethod(GET);

                conn.setRequestProperty(接收字符集,字符集);

                conn.setConnectTimeout(15000);

                conn.connect();

            }赶上(IOException异常E){
                e.printStackTrace();
            }

        }

        尝试 {
            //接收来自服务器的响应
            InputStream的时间=新的BufferedInputStream(conn.getInputStream());
            的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(在));
            结果=新的StringBuilder();
            串线;
            而((行= reader.readLine())!= NULL){
                result.append(线);
            }

            Log.d(JSON分析器,结果:+ result.toString());

        }赶上(IOException异常E){
            e.printStackTrace();
        }

        conn.disconnect();

        //尝试解析字符串到一个JSON对象
        尝试 {
            jObj =新的JSONObject(result.toString());
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }

        //返回JSON对象
        返回jObj;
    }
}
 
hive解析json

例的AsyncTask的帖子:

 类PostAsync扩展的AsyncTask<字符串,字符串,JSONObject的> {
    JSONParser jsonParser =新JSONParser();

    私人ProgressDialog pDialog;

    私有静态最后弦乐LOGIN_URL =htt​​p://www.example.com/testPost.php;

    私有静态最后弦乐TAG_SUCCESS =成功;
    私有静态最后弦乐TAG_MESSAGE =消息;


    @覆盖
    在preExecute保护无效(){
        pDialog =新ProgressDialog(MainActivity.this);
        pDialog.setMessage(试图登录......);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(真正的);
        pDialog.show();
    }

    @覆盖
    受保护的JSONObject doInBackground(字符串参数... args){

        尝试 {

            HashMap的<字符串,字符串> PARAMS =新的HashMap<>();
            params.put(名,ARGS [0]);
            params.put(密码,ARGS [1]);

            Log.d(要求,出发);

            JSONObject的JSON = jsonParser.makeHtt prequest(
                    LOGIN_URL,POST,则params);

            如果(JSON!= NULL){
                Log.d(JSON结果,json.toString());

                返回JSON;
            }

        }赶上(例外五){
            e.printStackTrace();
        }

        返回null;
    }

    保护无效onPostExecute(JSONObject的JSON){

        INT成功= 0;
        字符串消息=;

        如果(pDialog =空&安培;!&安培; pDialog.isShowing()){
            pDialog.dismiss();
        }

        如果(JSON!= NULL){
            Toast.makeText(MainActivity.this,json.toString(),
                    Toast.LENGTH_LONG).show();

            尝试 {
                成功= json.getInt(TAG_SUCCESS);
                消息= json.getString(TAG_MESSAGE);
            }赶上(JSONException E){
                e.printStackTrace();
            }
        }

        如果(成功== 1){
            Log.d(成功!,邮件);
        }其他{
            Log.d(失败,邮件);
        }
    }

}
 

例的AsyncTask的获取:

 类GetAsync扩展的AsyncTask<字符串,字符串,JSONObject的> {

    JSONParser jsonParser =新JSONParser();

    私人ProgressDialog pDialog;

    私有静态最后弦乐LOGIN_URL =htt​​p://www.example.com/testGet.php;

    私有静态最后弦乐TAG_SUCCESS =成功;
    私有静态最后弦乐TAG_MESSAGE =消息;

    @覆盖
    在preExecute保护无效(){
        pDialog =新ProgressDialog(MainActivity.this);
        pDialog.setMessage(试图登录......);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(真正的);
        pDialog.show();
    }

    @覆盖
    受保护的JSONObject doInBackground(字符串参数... args){

        尝试 {

            HashMap的<字符串,字符串> PARAMS =新的HashMap<>();
            params.put(名,ARGS [0]);
            params.put(密码,ARGS [1]);

            Log.d(要求,出发);

            JSONObject的JSON = jsonParser.makeHtt prequest(
                    LOGIN_URL,GET,PARAMS);

            如果(JSON!= NULL){
                Log.d(JSON结果,json.toString());

                返回JSON;
            }

        }赶上(例外五){
            e.printStackTrace();
        }

        返回null;
    }

    保护无效onPostExecute(JSONObject的JSON){

        INT成功= 0;
        字符串消息=;

        如果(pDialog =空&安培;!&安培; pDialog.isShowing()){
            pDialog.dismiss();
        }

        如果(JSON!= NULL){
            Toast.makeText(MainActivity.this,json.toString(),
                    Toast.LENGTH_LONG).show();

            尝试 {
                成功= json.getInt(TAG_SUCCESS);
                消息= json.getString(TAG_MESSAGE);
            }赶上(JSONException E){
                e.printStackTrace();
            }
        }

        如果(成功== 1){
            Log.d(成功!,邮件);
        }其他{
            Log.d(失败,邮件);
        }
    }

}
 

有关详细信息,下面是关于这code我的博客文章:的 http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html

I'm following this tutorial, and getting this error:

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.androidhive.materialtabs.adpater.JSONParser.makeHttpRequest(JSONParser.java:52)
                at info.androidhive.materialtabs.UserFunctions.loginUser(UserFunctions.java:37)
                at info.androidhive.materialtabs.activity.MainActivity$Login.doInBackground(MainActivity.java:551)
                at info.androidhive.materialtabs.activity.MainActivity$Login.doInBackground(MainActivity.java:519)

Here is the JSONParser class that I'm using:

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;
        }
}

解决方案

DefaultHttpClient was deprecated in api level 22, and removed in api level 23.

The documentation was even removed from the Android documentation, here is the link to where the documentation was previously, and you can see where it re-directs to: http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html

Quote just in case the re-direct changes:

Android 6.0 release 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.

I created an updated version of the JSONParser class that you're using, here it is:

import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

        conn.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jObj;
    }
}

Example AsyncTask for Post:

class PostAsync extends AsyncTask<String, String, JSONObject> {
    JSONParser jsonParser = new JSONParser();

    private ProgressDialog pDialog;

    private static final String LOGIN_URL = "http://www.example.com/testPost.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";


    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {

        try {

            HashMap<String, String> params = new HashMap<>();
            params.put("name", args[0]);
            params.put("password", args[1]);

            Log.d("request", "starting");

            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);

            if (json != null) {
                Log.d("JSON result", json.toString());

                return json;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(JSONObject json) {

        int success = 0;
        String message = "";

        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        if (json != null) {
            Toast.makeText(MainActivity.this, json.toString(),
                    Toast.LENGTH_LONG).show();

            try {
                success = json.getInt(TAG_SUCCESS);
                message = json.getString(TAG_MESSAGE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (success == 1) {
            Log.d("Success!", message);
        }else{
            Log.d("Failure", message);
        }
    }

}

Example AsyncTask for Get:

class GetAsync extends AsyncTask<String, String, JSONObject> {

    JSONParser jsonParser = new JSONParser();

    private ProgressDialog pDialog;

    private static final String LOGIN_URL = "http://www.example.com/testGet.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {

        try {

            HashMap<String, String> params = new HashMap<>();
            params.put("name", args[0]);
            params.put("password", args[1]);

            Log.d("request", "starting");

            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "GET", params);

            if (json != null) {
                Log.d("JSON result", json.toString());

                return json;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(JSONObject json) {

        int success = 0;
        String message = "";

        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        if (json != null) {
            Toast.makeText(MainActivity.this, json.toString(),
                    Toast.LENGTH_LONG).show();

            try {
                success = json.getInt(TAG_SUCCESS);
                message = json.getString(TAG_MESSAGE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (success == 1) {
            Log.d("Success!", message);
        }else{
            Log.d("Failure", message);
        }
    }

}

For more details, here's my blog post about this code: http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html