Android java.lang.NoSuchMethodError:没有为HttpClientResponse执行虚拟方法

Android java.lang.NoSuchMethodError:没有为HttpClientResponse执行虚拟方法,android,android-studio,httpresponse,apache-httpclient-4.x,nosuchmethoderror,Android,Android Studio,Httpresponse,Apache Httpclient 4.x,Nosuchmethoderror,当我尝试在启动后运行应用程序时,它在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/DefaultHttpClien

当我尝试在启动后运行应用程序时,它在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项目中使用HttpClient 4.5?转到,我发现Android用户使用的是适用于Android 4.3.5的HttpClient。我的项目将这些Jar文件用作库(不在gradle中编译)。你可以试着下载。希望这有帮助

是否不推荐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;
    }
@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 {
                ...
            }
        }
    }
MainActivity.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;
    }
@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 {
                ...
            }
        }
    }
@覆盖
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
新建APIRequest().execute();
}
私有类APIRequest扩展异步任务{
@凌驾
受保护对象doInBackground(无效…参数){
//当然,在测试一个案例时,您应该对其他案例进行注释
//案例1:对于FromBody参数
字符串url=”http://10.0.2.2/api/frombody";
String requestBody=Utils.buildPostParameters('FromBody Value');//FromBody参数必须有“”
HttpURLConnection-urlConnection=null;
试一试{
urlConnection=(HttpURLConnection)Utils.makeRequest(“POST”,url,null,“application/json”,requestBody);
if(urlConnection.getResponseCode()==HttpURLConnection.HTTP\u确定){
...
}否则{
...
}
...
返回响应;
}捕获(IOE异常){
e、 printStackTrace();
}最后{
if(urlConnection!=null){
urlConnection.disconnect();
}
}
//案例2:对于JSONObject参数
字符串url=”http://10.0.2.2/api/testjsonobject";
JSONObject jsonBody;
字符串请求体;
HttpURLConnection-urlConnection;
试一试{
jsonBody=新的JSONObject();
jsonBody.put(“标题”、“BNK标题”);
jsonBody.put(“作者”、“BNK”);
jsonBody.put(“日期”,“2015/08/08”);
requestBody=Utils.buildPostParameters(jsonBody);
urlConnection=(HttpURLConnection)Utils.makeRequest(“POST”,url,null,“application/json”,requestBody);
if(urlConnection.getResponseCode()==HttpURLConnection.HTTP\u确定){
...
}否则{
...
}
...
返回响应;
}捕获(JSONException | IOException e){
e、 printStackTrace();
}最后{
if(urlConnection!=null){
urlConnection.disconnect();
}
}           
//案例3:对于表单urlencoded参数
字符串url=”http://10.0.2.2/api/token";
HttpURLConnection-urlConnection;
Map stringMap=newhashmap();
stringMap.put(“授权类型”、“密码”);
stringMap.put(“用户名”、“用户名”);
stringMap.put(“密码”、“密码”);
String requestBody=Utils.buildPostParameters(stringMap);
试一试{
urlConnection=(HttpURLConnection)Utils.makeRequest(“POST”,url,null,“application/x-www-form-urlencoded”,requestBody);
JSONObject JSONObject=新的JSONObject();
试一试{
if(urlConnection.getResponseCode()==HttpURLConnection.HTTP\u确定){
...
}否则{
...
}                    
}捕获(IOException | JSONException e){
e、 printStackTrace();
}
返回jsonObject;
}捕获(例外e){
e、 printStackTrace();
}最后{
if(urlConnection!=null){
urlConnection.disconnect();
}
}
返回null;
}
@凌驾
受保护的void onPostExecute(对象响应){
super.onPostExecute(响应);
if(字符串的响应实例){
...               
}else if(JSONObject的响应实例){
...
}否则{
...
}
}
}

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

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

useLibrary 'org.apache.http.legacy'

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

感谢您的回复,但我到目前为止没有添加任何httpclient jar,在看到您的帖子后,我只添加了4.3.5 jar,尽管我得到了相同的错误@BNKTry use
HttpResponse HttpResponse
instead,但我也尝试了,但在执行HttpResponse=httpclient.execute(httpGet)时仍然因为空值而出错@BNKModified Code@BNK请看一看。由于不推荐使用,我建议您改用HttpUrlConnection或Volley库。可能是的副本