1

我使用了以下代码,但在执行 Asyntask 时出现错误,并且我已经发布了我的 JsonParser 类。请指导我如何删除此错误。

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

我还发布了我的 Asyntask 课程

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

                }

            }

        }

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;

            }
        }

我已将以下库包含到我的项目中。

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

下面是错误堆栈。

        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)
4

2 回答 2

6

在 build.gradle android 部分把这段代码
useLibrary 'org.apache.http.legacy'

然后您的应用程序将使用 Android/Sdk/platforms/android-23/optional 中的 org.apache.http.legacy.jar。崩溃的原因是 google 删除了对 Apache HTTP 客户端的支持,并建议使用 unstead HttpURLConnection 类。

以下是如何使用 HttpURLConnection 获取某些 url 内容的示例(例如,它可以是http://google.com?hacked=true):

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;
}
于 2015-12-01T15:27:27.973 回答
1

请尝试使用以下版本

HttpClient:httpclient-4.0-beta2.jar HttpCore:httpcore-4.1.jar

于 2015-10-29T12:07:19.803 回答