编程语言
首页 > 编程语言> > android-java.lang.NoSuchMethodError:HttpClientResponse没有执行虚拟方法

android-java.lang.NoSuchMethodError:HttpClientResponse没有执行虚拟方法

作者:互联网

当我尝试在启动后运行该应用程序时,它在logcat中显示异常,如下所示:

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)

调用execute方法后,类文件中出现错误.

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

在尝试调用execute()方法时,当我更改为HttpResponse并添加http-client-4.3.5.jar时,它的值为空.

如果不赞成,则不赞成使用execute()方法,使用post方法执行http连接调用的解决方案是什么?

请为我提供一些有关此错误的建议.
感谢您提前提出建议和答案!

解决方法:

您是否在Android项目中使用HttpClient 4.5?转到Apache,我发现对于Android,他们使用适用于Android 4.3.5的HttpClient.我的项目将这些Jar文件用作库(不在gradle中编译).您可以尝试下载here.希望这会有所帮助!

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

您可以参考以下示例代码:

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 {
                ...
            }
        }
    }

标签:nosuchmethoderror,android-studio,httpresponse,apache-httpclient-4-x,android
来源: https://codeday.me/bug/20191028/1948831.html