【问题标题】:java.lang.NoSuchMethodError: No virtual method execute for HttpClientResponsejava.lang.NoSuchMethodError:没有为 HttpClientResponse 执行虚拟方法
【发布时间】:2015-08-17 13:03:09
【问题描述】:

当我在启动后尝试运行应用程序时,它在 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 时,它得到了 null 值。

execute() 方法是否被弃用,如果是,使用 post 方法执行 http 连接调用的解决方案是什么。

请给我一些关于这个错误的建议。 提前感谢您的建议和回答!

【问题讨论】:

标签: android android-studio httpresponse apache-httpclient-4.x nosuchmethoderror


【解决方案1】:

以上解决方案对我不起作用。

useLibrary 'org.apache.http.legacy'

在 gradle 中添加这一行对我有用。

【讨论】:

    【解决方案2】:

    您在您的 Android 项目中使用 HttpClient 4.5 吗?转到Apache,我发现他们在Android 4.3.5 上使用HttpClient。我的项目使用这些 Jar 文件作为库(未在 gradle 中编译)。您可以尝试下载here。希望这会有所帮助!

    execute() 方法是否被弃用,如果是,使用 post 方法执行 http 连接调用的解决方案是什么。

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

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

    【讨论】:

    • 感谢您的回复,但到目前为止我没有添加任何 httpclient jar,在看到您的帖子后,我只是添加了 4.3.5 jar,即使我遇到了同样的错误@BNK
    • 尝试改用HttpResponse httpResponse
    • 我也试过了,但在执行 httpResponse = httpClient.execute(httpGet); 时仍然因为空值而出错@BNK
    • 修改代码@BNK请看一下。
    • 因为弃用,建议你改用HttpUrlConnection,或者Volley库。
    【解决方案3】:

    尝试将您正在使用的 android sdk 版本更改为 Marshmallow 之前的版本,并从您的项目中删除 apache jar 文件。这些类已经在 sdk 中可用。

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      相关资源
      最近更新 更多