Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.NoSuchMethodError: No virtual method execute for HttpClientResponse

When I try to run the app after launching it is showing exception in logcat like this:

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)

In class file is getting error after calling execute method.

CloseableHttpResponse httpResponse = null;

httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(strServiceURL);
//When executing the below line get null value for response.
httpResponse = httpClient.execute(httpGet);  
httpEntity = httpResponse.getEntity();
responsePayload = EntityUtils.toString(httpEntity);

While trying to call execute() method it's getting null value when I change to HttpResponse and by adding http-client-4.3.5.jar.

Whether execute() method is deprecated if so what is the solution to execute the http connection call using post method.

Please provide me some suggestions for this error. Thanks for suggestions and answers in advance!

like image 283
Danny Avatar asked Mar 15 '23 01:03

Danny


2 Answers

Above solutions did not work for me.

useLibrary 'org.apache.http.legacy'

Adding this line in gradle worked for me.

like image 101
Ramesh Avatar answered Apr 29 '23 11:04

Ramesh


Do you use HttpClient 4.5 in your Android project? Go to Apache, I have found for Android they use HttpClient for Android 4.3.5. My projects use these Jar files as library (not compiled in gradle). You can try download here. Hope this helps!

Whether execute() method is deprecated if so what is the solution to execute the http connection call using post method.

You can refer to the following sample code:

Utils.java:

public static String buildPostParameters(Object content) {
        String output = null;
        if ((content instanceof String) ||
                (content instanceof JSONObject) ||
                (content instanceof JSONArray)) {
            output = content.toString();
        } else if (content instanceof Map) {
            Uri.Builder builder = new Uri.Builder();
            HashMap hashMap = (HashMap) content;
            if (hashMap != null) {
                Iterator entries = hashMap.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                    entries.remove(); // avoids a ConcurrentModificationException
                }
                output = builder.build().getEncodedQuery();
            }
        }

        return output;
    }

public static URLConnection makeRequest(String method, String apiAddress, String accessToken, String mimeType, String requestBody) throws IOException {
        URL url = new URL(apiAddress);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(!method.equals("GET"));
        urlConnection.setRequestMethod(method);

        urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);        

        urlConnection.setRequestProperty("Content-Type", mimeType);
        OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
        writer.write(requestBody);
        writer.flush();
        writer.close();
        outputStream.close();            

        urlConnection.connect();

        return urlConnection;
    }

MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new APIRequest().execute();
}

private class APIRequest extends AsyncTask<Void, Void, Object> {

        @Override
        protected Object doInBackground(Void... params) {

            // Of course, you should comment the other CASES when testing one CASE

            // CASE 1: For FromBody parameter
            String url = "http://10.0.2.2/api/frombody";
            String requestBody = Utils.buildPostParameters("'FromBody Value'"); // must have '' for FromBody parameter
            HttpURLConnection urlConnection = null;
            try {
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);                    
                if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    ...
                } else {
                    ...
                }
                ...
                return response;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

            // CASE 2: For JSONObject parameter
            String url = "http://10.0.2.2/api/testjsonobject";
            JSONObject jsonBody;
            String requestBody;
            HttpURLConnection urlConnection;
            try {
                jsonBody = new JSONObject();
                jsonBody.put("Title", "BNK Title");
                jsonBody.put("Author", "BNK");
                jsonBody.put("Date", "2015/08/08");
                requestBody = Utils.buildPostParameters(jsonBody);
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);                    
                if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                     ...
                } else {
                    ...
                }
                ...
                return response;
            } catch (JSONException | IOException e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }           

            // CASE 3: For form-urlencoded parameter
            String url = "http://10.0.2.2/api/token";
            HttpURLConnection urlConnection;
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("grant_type", "password");
            stringMap.put("username", "username");
            stringMap.put("password", "password");
            String requestBody = Utils.buildPostParameters(stringMap);
            try {
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/x-www-form-urlencoded", requestBody);
                JSONObject jsonObject = new JSONObject();
                try {
                    if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        ...
                    } else {
                        ...
                    }                    
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
                return jsonObject;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(Object response) {
            super.onPostExecute(response);
            if (response instanceof String) {
                ...               
            } else if (response instanceof JSONObject) {
                ...
            } else {
                ...
            }
        }
    }
like image 31
BNK Avatar answered Apr 29 '23 12:04

BNK