在使用中的AsyncTask得到错误的HttpClient和HTTP核心库核心、错误、AsyncTask、HTTP

2023-09-07 00:05:54 作者:暮光沉寂i

我用下面的code,但执行Asyntask,也是我已经发布我JsonParser class.Please指导我如何删除这个错误时,它提供的错误。

 公共类扩展登录活动实现OnClickListener {            私人用户的EditText,通过;            私人按钮mSubmit,mRegister;            私人ProgressDialog pDialog;            // JSON解析器类            JSONParser jsonParser =新JSONParser();             私有静态最后弦乐LOGIN_URL =HTTP://******/web_service/index.php           //www.itsoft-solutions.net            //从PHP脚本repsonse JSON元素ID:            私有静态最后弦乐TAG_SUCCESS =成功;            私有静态最后弦乐TAG_MESSAGE =消息;            公共静态字符串的uname;            公共静态字符串密码;            @覆盖            保护无效的onCreate(捆绑savedInstanceState){                // TODO自动生成方法存根                super.onCreate(savedInstanceState);                的setContentView(R.layout.login);                字符串的uname,PWD;                //设置输入字段                用户=(EditText上)findViewById(R.id.username);                通=(EditText上)findViewById(R.id.password);                //设置按钮                mSubmit =(按钮)findViewById(R.id.login);                mRegister =(按钮)findViewById(R.id.register);                //注册监听器                mSubmit.setOnClickListener(本);                mRegister.setOnClickListener(本);            }            @覆盖            公共无效的onClick(视图v){                // TODO自动生成方法存根                开关(v.getId()){                    案例R.id.login:                         新AttemptLogin(user.getText()的toString(),pass.getText()的toString()。)的execute()。                        打破;                    案例R.id.register:                        意图I =新意图(这一点,Register.class);                        startActivity(ⅰ);                        打破;                    默认:                        打破;                }            } 

和我也张贴了我的Asyntask类

 类AttemptLogin扩展的AsyncTask<字符串,字符串,字符串> {                布尔失败= F​​ALSE;                字符串的uname,PWD;                公共AttemptLogin(用户名字符串,字符串密码){                    的uname =用户名;                    PWD =密码;                }                @覆盖                在preExecute保护无效(){                    super.on preExecute();                    pDialog =新ProgressDialog(Login.this);                    pDialog.setMessage(试图登录...);                    pDialog.setIndeterminate(假);                    pDialog.setCancelable(真);                    pDialog.show();                }                @覆盖                保护字符串doInBackground(字符串参数... args){                    // TODO自动生成方法存根                    //检查成功标记                    诠释成功;                    尝试{                        //大厦参数                        清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();                        params.add(新BasicNameValuePair(用户名,UNAME));                        params.add(新BasicNameValuePair(密码,PWD));                        Log.d(!要求,出发);                        //通过HTTP请求获得产品的详细信息                        JSONObject的JSON = jsonParser.makeHtt prequest(                                LOGIN_URL,POST,则params);                        //检查你的日志,JSON响应                        Log.d(登录尝试,json.toString());                        // JSON的成功标签                        成功= json.getInt(TAG_SUCCESS);                        如果(成功== 1){                            Log.d(登录成功!,json.toString());                            意图I =新意图(Login.this,ReadComments.class);                            完();                            startActivity(ⅰ);                            返回json.getString(TAG_MESSAGE);                        }其他{                            Log.d(登录失败!,json.getString(TAG_MESSAGE));                            返回json.getString(TAG_MESSAGE);                        }                    }赶上(JSONException E){                        e.printStackTrace();                    }                    返回null;                }                / **                 *在完成后台任务之后辞退进度对话框                 ** /                保护无效onPostExecute(字符串FILE_URL){                    //关闭该对话框一旦产品被删除                    pDialog.dismiss();                    如果(FILE_URL!= NULL){                        Toast.makeText(Login.this,FILE_URL,Toast.LENGTH_LONG).show();                    }                }            }        } 

以下code在JSONParser.java

 包com.example.mysqltest;        公共类JSONParser {            静态InputStream为= NULL;            静态的JSONObject jObj = NULL;            静态JSON字符串=;            //构造            公共JSONParser(){            }            //函数得到JSON的网址            //通过HTTP POST或GET mehtod            公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,                    清单<&的NameValuePair GT; 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(参数,可以UTF-8);                        网址+ =? +中的paramString;                        HTTPGET HTTPGET =新HTTPGET(URL);                        HTT presponse HTT presponse = httpClient.execute(HTTPGET);                        HttpEntity httpEntity = HTT presponse.getEntity();                        是= httpEntity.getContent();                    }                }赶上(UnsupportedEncodingException五){                    e.printStackTrace();                }赶上(ClientProtocolException E){                    e.printStackTrace();                }赶上(IOException异常五){                    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;            }        } 
如何在Android开发中用AsyncTask异步更新UI界面

我已经包括以下库我的项目。

  1的HttpClient-4.5.jar    2.的HttpCore-4.4.1.jar 

下面是错误堆栈。

  09-01 14:22:44.365 16257-16869 / com.example.mysqltest E / AndroidRuntime:致命的异常:AsyncTask的#3            工艺:com.example.mysqltest,PID:16257            了java.lang.RuntimeException:执行doInBackground发生错误()                    在android.os.AsyncTask $ 3.done(AsyncTask.java:300)                    在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)                    在java.util.concurrent.FutureTask.setException(FutureTask.java:222)                    在java.util.concurrent.FutureTask.run(FutureTask.java:242)                    在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)                    在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)                    在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:587)                    在java.lang.Thread.run(Thread.java:818)             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)                    在com.example.mysqltest.JSONParser.makeHtt prequest(JSONParser.java:52)                    在com.example.mysqltest.Login $ AttemptLogin.doInBackground(Login.java:136)                    在com.example.mysqltest.Login $ AttemptLogin.doInBackground(Login.java:96)                    在android.os.AsyncTask $ 2.call(AsyncTask.java:288)                    在java.util.concurrent.FutureTask.run(FutureTask.java:237)        在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)        在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)        在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:587)        在java.lang.Thread.run(Thread.java:818) 

解决方案

在Android版的build.gradle节把这个code结果 useLibrary'org.apache.http.legacy

那么你的应用程序将使用org.apache.http.legacy.jar这是Android的/ SDK /平台/ Android的23 /可选。之所以崩溃是,谷歌移除支持的Apache HTTP客户端,并使用unstead HttpURLConnection类类建议。

下面是一个示例如何让使用HttpURLConnection类的一些网址的内容(也可以是 http://google.com?砍死= TRUE 为例):

 公共静态字符串的file_get_contents(字符串fileURL)        抛出异常{    Log.d(的file_get_contents,让网址+ fileURL);    字符串结果=;    网址URL =新的URL(fileURL);    HttpURLConnection的httpConn =(HttpURLConnection类)url.openConnection();    INT响应code = httpConn.getResponse code();    //总是先检查HTTP响应code    如果(响应code == HttpURLConnection.HTTP_OK){        字符串文件名=;        字符串处置= httpConn.getHeaderField(内容处置);        字符串的contentType = httpConn.getContentType();        INT CONTENTLENGTH = httpConn.getContentLength();        如果(处置!= NULL){            //提取物头字段文件名            INT指数= disposition.indexOf(文件名=);            如果(指数大于0){                文件名= disposition.substring(指数+ 10,                        disposition.length() -  1);            }        }其他{            //提取物URL文件名            文件名= fileURL.substring(fileURL.lastIndexOf(/)+ 1,                    fileURL.length());        }        Log.d(的file_get_contents,内容类型=+的contentType);        Log.d(的file_get_contents,内容处置=+处置);        Log.d(的file_get_contents,内容长度=+ CONTENTLENGTH);        Log.d(的file_get_contents,文件名=+文件名);        //从HTTP连接打开输入流        为InputStream的InputStream = httpConn.getInputStream();        INT读取动作= -1;        字节[]缓冲区=新的字节[BUFFER_SIZE];        而((读取动作= inputStream.read(缓冲液))!=  -  1){            Log.d(的file_get_contents,字节读:+读取动作);            串bufferString =新串(缓冲液,0,读取动作,UTF-8);            Log.d(的file_get_contents,缓冲器字符串:+ bufferString);            结果= result.concat(bufferString);            //outputStream.write(buffer,0,读取动作);        }        //outputStream.close();        inputStream.close();        Log.d(的file_get_contents,文件下载);    }其他{        Log.d(的file_get_contents,没有文件下载服务器回答HTTP code:+响应code);    }    httpConn.disconnect();    Log.d(的file_get_contents,返回+结果);    返回结果;} 

I have used the following code but it gives error when executing the Asyntask and also I have posted my JsonParser class.Please guide me how can i remove this error.

        public class Login extends Activity implements OnClickListener {

            private EditText user, pass;
            private Button mSubmit, mRegister;
            private ProgressDialog pDialog;
            // JSON parser class
            JSONParser jsonParser = new JSONParser();
             private static final String LOGIN_URL = "http://******/web_service/index.php";
           //www.itsoft-solutions.net
            //JSON element ids from repsonse of php script:
            private static final String TAG_SUCCESS = "success";
            private static final String TAG_MESSAGE = "message";
            public static String uname;
            public static String password;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);
                setContentView(R.layout.login);
                String uName, pwd;
                //setup input fields
                user = (EditText) findViewById(R.id.username);
                pass = (EditText) findViewById(R.id.password);
                //setup buttons
                mSubmit = (Button) findViewById(R.id.login);
                mRegister = (Button) findViewById(R.id.register);
                //register listeners
                mSubmit.setOnClickListener(this);
                mRegister.setOnClickListener(this);

            }

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                switch (v.getId()) {
                    case R.id.login:
                         new AttemptLogin(user.getText().toString(), pass.getText().toString()).execute();
                        break;
                    case R.id.register:
                        Intent i = new Intent(this, Register.class);
                        startActivity(i);
                        break;

                    default:
                        break;
                }
            }

and I have also posted my Asyntask class

            class AttemptLogin extends AsyncTask<String, String, String> {

                boolean failure = false;
                String uName, pwd;
                public AttemptLogin(String userName, String password) {
                    uName = userName;
                    pwd = password;
                }

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

                @Override
                protected String doInBackground(String... args) {
                    // TODO Auto-generated method stub
                    // Check for success tag
                    int success;

                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("username", uName));
                        params.add(new BasicNameValuePair("password", pwd));

                        Log.d("request!", "starting");
                        // getting product details by making HTTP request
                        JSONObject json = jsonParser.makeHttpRequest(
                                LOGIN_URL, "POST", params);

                        // check your log for json response
                        Log.d("Login attempt", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            Log.d("Login Successful!", json.toString());
                            Intent i = new Intent(Login.this, ReadComments.class);
                            finish();
                            startActivity(i);
                            return json.getString(TAG_MESSAGE);
                        } else {
                            Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                            return json.getString(TAG_MESSAGE);

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

                    return null;

                }

                /**
                 * After completing background task Dismiss the progress dialog
                 **/
                protected void onPostExecute(String file_url) {
                    // dismiss the dialog once product deleted
                    pDialog.dismiss();
                    if (file_url != null) {
                        Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
                    }

                }

            }

        }

The following code in the JSONParser.java

        package com.example.mysqltest;

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

            }
        }

I have included the following library to my project.

    1. httpclient-4.5.jar
    2. httpcore-4.4.1.jar

Below is the error stack.

        09-01 14:22:44.365  16257-16869/com.example.mysqltest E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
            Process: com.example.mysqltest, PID: 16257
            java.lang.RuntimeException: An error occured while executing doInBackground()
                    at android.os.AsyncTask$3.done(AsyncTask.java:300)
                    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                    at java.lang.Thread.run(Thread.java:818)
             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 com.example.mysqltest.JSONParser.makeHttpRequest(JSONParser.java:52)
                    at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:136)
                    at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:96)
                    at android.os.AsyncTask$2.call(AsyncTask.java:288)
                    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                    at java.lang.Thread.run(Thread.java:818)

解决方案

in build.gradle android section put this code useLibrary 'org.apache.http.legacy'

Then your application will use org.apache.http.legacy.jar which is in Android/Sdk/platforms/android-23/optional. The reason for crash is that google removed support of Apache HTTP client and suggests using unstead HttpURLConnection class.

Here's a sample how to get content of some url using HttpURLConnection (it can be http://google.com?hacked=true, for example):

public static String file_get_contents(String fileURL)
        throws Exception {

    Log.d("file_get_contents", "getting url " + fileURL);
    String result = "";
    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();

    // always check HTTP response code first
    if (responseCode == HttpURLConnection.HTTP_OK) {
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        String contentType = httpConn.getContentType();
        int contentLength = httpConn.getContentLength();

        if (disposition != null) {
            // extracts file name from header field
            int index = disposition.indexOf("filename=");
            if (index > 0) {
                fileName = disposition.substring(index + 10,
                        disposition.length() - 1);
            }
        } else {
            // extracts file name from URL
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                    fileURL.length());
        }

        Log.d("file_get_contents", "Content-Type = " + contentType);
        Log.d("file_get_contents", "Content-Disposition = " + disposition);
        Log.d("file_get_contents", "Content-Length = " + contentLength);
        Log.d("file_get_contents", "fileName = " + fileName);

        // opens input stream from the HTTP connection
        InputStream inputStream = httpConn.getInputStream();

        int bytesRead = -1;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            Log.d("file_get_contents", "bytes read: " + bytesRead);
            String bufferString = new String(buffer, 0, bytesRead, "UTF-8");
            Log.d("file_get_contents", "buffer string: " + bufferString);
            result = result.concat(bufferString);
            //outputStream.write(buffer, 0, bytesRead);
        }

        //outputStream.close();
        inputStream.close();

        Log.d("file_get_contents", "File downloaded");
    } else {
        Log.d("file_get_contents", "No file to download. Server replied HTTP code: " + responseCode);
    }
    httpConn.disconnect();

    Log.d("file_get_contents", "returning " + result);
    return result;
}