【问题标题】:HttpClient won't import in Android StudioHttpClient 不会在 Android Studio 中导入
【发布时间】:2015-11-16 03:58:50
【问题描述】:

我有一个用 Android Studio 编写的简单类:

package com.mysite.myapp;

import org.apache.http.client.HttpClient;

public class Whatever {
    public void headBangingAgainstTheWallExample () {
        HttpClient client = new DefaultHttpClient();
    }
}

由此我得到以下编译时错误:

Cannot resolve symbol HttpClient

HttpClient 不是包含在 Android Studio SDK 中吗?即使不是,我也将它添加到我的 Gradle 构建中,如下所示:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'org.apache.httpcomponents:httpclient:4.5'
}

不管有没有最后的编译行,错误都是一样的。我错过了什么?

【问题讨论】:

  • 如果可以,请尝试使用AndroidHttpClient。 HttpClient 存根确实包含在 android jar 中,因此不需要显式引用它。注意httpclient的android版本大概是4.1.1。尝试在此基础上使用较新的版本通常是自找麻烦(阅读:不起作用,因为固件类加载器总是获胜)。

标签: android gradle android-gradle-plugin apache-httpclient-4.x


【解决方案1】:

sdk 23 不再支持HttpClient。您必须使用URLConnection 或降级到sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')

如果您需要 sdk 23,请将其添加到您的 gradle:

android {
    useLibrary 'org.apache.http.legacy'
}

您也可以尝试下载HttpClient jar 并将其直接包含到您的项目中,或者改用OkHttp

【讨论】:

  • 在我的情况下它没有做任何事情。怎么会?
  • useLibrary 添加时无法解析。我的目标是 23 岁,我错过了什么?
  • android { useLibrary 'org.apache.http.legacy' } [当你添加这个] [1] 'org.apache.http' android-studio 还是有提示:'不能解析符号' [2] 这使得 android-studio(with sdk23) 可以构建。虽然有提示(无法解析符号)[3] 如果你添加 jar,它没有提示,可以构建,但是!!!不能运行,因为它有两个副本 'org.apache.http'
  • 对于使用 Volley 库的任何人,请注意,此 gradle 行添加应该进入库的 gradle 文件,而不是您的应用程序。完美运行!非常感谢!
【解决方案2】:

HttpClient 在 API 级别 22 中已被弃用,并在 API 级别 23 中被删除。如果必须,您仍然可以在 API 级别 23 及更高版本中使用它,但是最好转向支持的方法来处理 HTTP。因此,如果您使用 23 进行编译,请将其添加到您的 build.gradle 中:

android {
    useLibrary 'org.apache.http.legacy'
}

【讨论】:

  • android { useLibrary 'org.apache.http.legacy' } [当你添加这个] [1] 'org.apache.http' android-studio 还有提示:'不能解析符号' [2] 这使得 android-studio(with sdk23) 可以构建。虽然有提示(无法解析符号)[3] 如果你添加 jar,它没有提示,可以构建,但是!!!不能运行,因为它有两个副本 'org.apache.http'
  • [2.1] 所以关闭 Android Studio 并重新启动它,不要打开使用旧代码的文件,“提示”不会'不能应用。如果您需要打开该文件,那么它建议您拥有该代码,因此[4]您应该停止在您控制的代码中使用 HttpClient。
  • 不知道为什么 (build-tool&sdk)23 的行为如此怪异。事件不支持开发者随意使用“apche http”。
  • 您必须将android studio更新到最新版本以避免这种行为......它已在新版本中修复
  • “支持的 HTTP 处理方法”有哪些?
【解决方案3】:

TejaDroid 在以下链接中的回答帮助了我。 Can't import org.apache.http.HttpResponse in Android Studio

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.0.1'

    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    ...
}

【讨论】:

  • 感谢这是唯一适用于新实验版本的解决方案,因为其中无法识别 useLibrary
  • 这其实是比上面那个更好的答案!它适用于较新版本的编译器
【解决方案4】:

将 Apache HTTP 用于 SDK 级别 23:

顶级 build.gradle - /build.gradle

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0' 
        // Lowest version for useLibrary is 1.3.0
        // Android Studio will notify you about the latest stable version
        // See all versions: http://jcenter.bintray.com/com/android/tools/build/gradle/
    }
    ...
}

来自 Android Studio 的关于 gradle 更新的通知:

模块特定的 build.gradle - /app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

【讨论】:

    【解决方案5】:

    试试这个 为我工作 将此依赖项添加到您的 build.gradle 文件中

    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    

    【讨论】:

      【解决方案6】:

      1- 从
      https://hc.apache.org/downloads.cgi?Preferred=http%3A%2F%2Fapache.arvixe.com%2F

      下载 Apache jar 文件(截至本答案)4.5.zip 文件

      2- 打开 zip 将 jar 文件复制到您的 libs 文件夹中。如果您转到项目顶部的“Android”,您可以找到它,当您单击它时,您会找到一个列表。所以,

      Android -> 项目 -> 应用程序 -> 库

      ,然后把罐子放在那里。

      3- 在 build.gradle (Module: app) 中添加

      compile fileTree(dir: 'libs', include: ['*.jar'])
      

       dependency { 
         }
      

      4- 在 java 类中添加这些导入:

      import org.apache.http.HttpResponse;
      
      import org.apache.http.client.HttpClient;
      
      import org.apache.http.client.methods.HttpGet;
      
      import org.apache.http.impl.client.DefaultHttpClient;
      
      import org.apache.http.params.CoreProtocolPNames;
      

      【讨论】:

        【解决方案7】:

        sdk 23 不再支持 HttpClient。Android 6.0(API 级别 23)版本删除了对 Apache HTTP 客户端的支持。 你必须使用

        android {
            useLibrary 'org.apache.http.legacy'
            .
            .
            .
        

        并在您的依赖项中添加以下代码 sn-p :

        //http web-service的最终解决方案(包括文件上传)

        compile('org.apache.httpcomponents:httpmime:4.3.6') {
                exclude module: 'httpclient'
        }
         compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
        

        当您使用 MultipartEntity 进行 文件上传 时,它也会对您有所帮助。

        【讨论】:

        • 很高兴听到它对您有帮助 :)
        • 我对此有疑问...重复条目:org/apache/http/HttpHeaders.class。你知道是什么问题吗?
        【解决方案8】:

        在 API 22 中它们已被弃用,而在 API 23 中它们完全删除了它们,如果您不需要新添加的所有花哨的东西,一个简单的解决方法是简单地使用在 API 之前集成的 apache 中的 .jar 文件22,但作为单独的 .jar 文件:

        1. http://hc.apache.org/downloads.cgi
        2. download httpclient 4.5.1, the zile file
        3. unzip all files
        4. drag in your project httpclient-4.5.1.jar, httpcore-4.4.3.jar and httpmime-4.5.1.jar
        5. project, right click, open module settings, app, dependencies, +, File dependency and add the 3 files
        6. now everything should compile properly
        

        【讨论】:

          【解决方案9】:

          如果你想导入一些类,比如:

          import org.apache.http.NameValuePair;
          import org.apache.http.client.HttpClient; 
          import org.apache.http.client.entity.UrlEncodedFormEntity;
          import org.apache.http.client.methods.HttpPost;
          import org.apache.http.impl.client.DefaultHttpClient;
          import org.apache.http.message.BasicNameValuePair;
          import org.apache.http.params.BasicHttpParams;
          import org.apache.http.params.HttpConnectionParams;
          import org.apache.http.params.HttpParams;
          

          可以在build.gradle(Gradle依赖)中添加如下一行

          dependencies {
              implementation fileTree(dir: 'libs', include: ['*.jar'])
              implementation 'com.android.support:appcompat-v7:27.1.0'
              implementation 'com.android.support:support-v4:27.1.0'
          
              .
              .
              .
          
              implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
          
          }
          

          【讨论】:

          • 完美答案!我不得不使用 Wrapped.org.apache,因为我需要更新一个非常古老的项目。谢谢。
          【解决方案10】:

          您可以简单地将其添加到 Gradle 依赖项中:

          compile "org.apache.httpcomponents:httpcore:4.3.2"
          

          【讨论】:

          • 这有帮助。但是如果你想使用其他类,比如HttpGet,还是不够的。为此我使用了compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
          【解决方案11】:

          Android 6.0(API 级别 23)版本删除了对 Apache HTTP 客户端的支持。因此你不能直接在 API 23 中使用这个库。但是有一种方法可以使用它。在您的 build.gradle 文件中添加 useLibrary ‘org.apache.http.legacy’,如下所示-

          android {
              useLibrary 'org.apache.http.legacy'
          }
          

          如果这不起作用,您可以应用以下 hack-

          – 将 Android SDK 目录 /platforms/android-23/optional 路径中的 org.apache.http.legacy.jar 复制到项目的 app/libs 文件夹中。

          – 现在在 build.gradle 文件的 dependencies{} 部分中添加编译文件(‘libs/org.apache.http.legacy.jar’)。

          【讨论】:

          • 您提供的最后一个选项做得很好。我很感激。
          【解决方案12】:

          ApacheHttp 客户端在 v23 sdk 中被移除。您可以使用 HttpURLConnection 或 OkHttp 等第三方 Http Client。

          参考:https://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client

          【讨论】:

          • 实际上鼓励使用HttpUrlConnection 代替HttpClient
          【解决方案13】:

          你只需要添加一行

          useLibrary 'org.apache.http.legacy'
          

          进入build.gradle(Module:app),例如

          apply plugin: 'com.android.application'
          
          android {
              compileSdkVersion 24
              buildToolsVersion "25.0.0"
          
              useLibrary 'org.apache.http.legacy'
          
              defaultConfig {
                  applicationId "com.avenues.lib.testotpappnew"
                  minSdkVersion 15
                  targetSdkVersion 24
                  versionCode 1
                  versionName "1.0"
                  testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
              }
              buildTypes {
                  release {
                      minifyEnabled false
                      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                  }
              }
          }
          
          dependencies {
              compile fileTree(dir: 'libs', include: ['*.jar'])
              androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
                  exclude group: 'com.android.support', module: 'support-annotations'
              })
              compile 'com.android.support:appcompat-v7:24.2.1'
              testCompile 'junit:junit:4.12'
          }
          

          【讨论】:

            【解决方案14】:

            只需使用这个:-

            android {
                     .
                     .
                     .
             useLibrary 'org.apache.http.legacy'
                     .
                     .
                     .
                      }
            

            【讨论】:

              【解决方案15】:

              sdk 23 和 23+ 不支持 HttpClient。

              如果您需要使用到 sdk 23,请将以下代码添加到您的 gradle:

              android {
                  useLibrary 'org.apache.http.legacy'
              }
              

              它对我有用。希望对你有用。

              【讨论】:

              • 与 SDK 24 版完美配合
              【解决方案16】:

              如果您需要 sdk 23,请将其添加到您的 gradle:

              android {
                  useLibrary 'org.apache.http.legacy'
              }
              

              【讨论】:

                【解决方案17】:

                您的项目中有哪个 API 目标?AndroidHttpClient仅适用于 API 级别 8 here

                享受你的代码吧:)

                【讨论】:

                  【解决方案18】:

                  如前所述,org.apache.http.client.HttpClient 不再支持:

                  SDK(API 级别)#23。

                  你必须使用java.net.HttpURLConnection

                  如果您想在使用HttpURLConnection 时使您的代码(和生活)更轻松,这里有一个此类的Wrapper,它可以让您使用GETPOSTPUT 进行简单操作JSON,例如,做一个HTTP PUT

                  HttpRequest request = new HttpRequest(API_URL + PATH).addHeader("Content-Type", "application/json");
                  int httpCode = request.put(new JSONObject().toString());
                  if (HttpURLConnection.HTTP_OK == httpCode) {
                      response = request.getJSONObjectResponse();
                  } else {
                    // log error
                  }
                  httpRequest.close()
                  

                  请随意使用。

                  package com.calculistik.repository;
                  
                  import java.io.BufferedReader;
                  import java.io.BufferedWriter;
                  import java.io.ByteArrayOutputStream;
                  import java.io.IOException;
                  import java.io.InputStream;
                  import java.io.InputStreamReader;
                  import java.io.OutputStream;
                  import java.io.OutputStreamWriter;
                  import java.net.HttpURLConnection;
                  import java.net.URL;
                  import java.util.HashMap;
                  import java.util.Map;
                  
                  import org.json.JSONArray;
                  import org.json.JSONException;
                  import org.json.JSONObject;
                  
                  /**
                   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
                   * <p>
                   * Copyright © 2017, Calculistik . All rights reserved.
                   * <p>
                   * Oracle and Java are registered trademarks of Oracle and/or its
                   * affiliates. Other names may be trademarks of their respective owners.
                   * <p>
                   * The contents of this file are subject to the terms of either the GNU
                   * General Public License Version 2 only ("GPL") or the Common
                   * Development and Distribution License("CDDL") (collectively, the
                   * "License"). You may not use this file except in compliance with the
                   * License. You can obtain a copy of the License at
                   * https://netbeans.org/cddl-gplv2.html or
                   * nbbuild/licenses/CDDL-GPL-2-CP. See the License for the specific
                   * language governing permissions and limitations under the License.
                   * When distributing the software, include this License Header
                   * Notice in each file and include the License file at
                   * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this particular file
                   * as subject to the "Classpath" exception as provided by Oracle in the
                   * GPL Version 2 section of the License file that accompanied this code. If
                   * applicable, add the following below the License Header, with the fields
                   * enclosed by brackets [] replaced by your own identifying information:
                   * "Portions Copyrighted [year] [name of copyright owner]"
                   * <p>
                   * Contributor(s):
                   * Created by alejandro tkachuk @aletkachuk
                   * www.calculistik.com
                   */
                  public class HttpRequest {
                  
                      public static enum Method {
                          POST, PUT, DELETE, GET;
                      }
                  
                      private URL url;
                      private HttpURLConnection connection;
                      private OutputStream outputStream;
                      private HashMap<String, String> params = new HashMap<String, String>();
                  
                      public HttpRequest(String url) throws IOException {
                          this.url = new URL(url);
                          connection = (HttpURLConnection) this.url.openConnection();
                      }
                  
                      public int get() throws IOException {
                          return this.send();
                      }
                  
                      public int post(String data) throws IOException {
                          connection.setDoInput(true);
                          connection.setRequestMethod(Method.POST.toString());
                          connection.setDoOutput(true);
                          outputStream = connection.getOutputStream();
                          this.sendData(data);
                          return this.send();
                      }
                  
                      public int post() throws IOException {
                          connection.setDoInput(true);
                          connection.setRequestMethod(Method.POST.toString());
                          connection.setDoOutput(true);
                          outputStream = connection.getOutputStream();
                          return this.send();
                      }
                  
                      public int put(String data) throws IOException {
                          connection.setDoInput(true);
                          connection.setRequestMethod(Method.PUT.toString());
                          connection.setDoOutput(true);
                          outputStream = connection.getOutputStream();
                          this.sendData(data);
                          return this.send();
                      }
                  
                      public int put() throws IOException {
                          connection.setDoInput(true);
                          connection.setRequestMethod(Method.PUT.toString());
                          connection.setDoOutput(true);
                          outputStream = connection.getOutputStream();
                          return this.send();
                      }
                  
                      public HttpRequest addHeader(String key, String value) {
                          connection.setRequestProperty(key, value);
                          return this;
                      }
                  
                      public HttpRequest addParameter(String key, String value) {
                          this.params.put(key, value);
                          return this;
                      }
                  
                      public JSONObject getJSONObjectResponse() throws JSONException, IOException {
                          return new JSONObject(getStringResponse());
                      }
                  
                      public JSONArray getJSONArrayResponse() throws JSONException, IOException {
                          return new JSONArray(getStringResponse());
                      }
                  
                      public String getStringResponse() throws IOException {
                          BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                          StringBuilder response = new StringBuilder();
                          for (String line; (line = br.readLine()) != null; ) response.append(line + "\n");
                          return response.toString();
                      }
                  
                      public byte[] getBytesResponse() throws IOException {
                          byte[] buffer = new byte[8192];
                          InputStream is = connection.getInputStream();
                          ByteArrayOutputStream output = new ByteArrayOutputStream();
                          for (int bytesRead; (bytesRead = is.read(buffer)) >= 0; )
                              output.write(buffer, 0, bytesRead);
                          return output.toByteArray();
                      }
                  
                      public void close() {
                          if (null != connection)
                              connection.disconnect();
                      }
                  
                      private int send() throws IOException {
                          int httpStatusCode = HttpURLConnection.HTTP_BAD_REQUEST;
                  
                          if (!this.params.isEmpty()) {
                              this.sendData();
                          }
                          httpStatusCode = connection.getResponseCode();
                  
                          return httpStatusCode;
                      }
                  
                      private void sendData() throws IOException {
                          StringBuilder result = new StringBuilder();
                          for (Map.Entry<String, String> entry : params.entrySet()) {
                              result.append((result.length() > 0 ? "&" : "") + entry.getKey() + "=" + entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
                          }
                          sendData(result.toString());
                      }
                  
                      private HttpRequest sendData(String query) throws IOException {
                          BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                          writer.write(query);
                          writer.close();
                          return this;
                      }
                  
                  }
                  

                  【讨论】:

                    【解决方案19】:

                    在依赖项下添加这两行

                    compile 'org.apache.httpcomponents:httpcore:4.4.1'
                    compile 'org.apache.httpcomponents:httpclient:4.5'
                    

                    然后

                    useLibrary 'org.apache.http.legacy'
                    

                    android下

                    【讨论】:

                      【解决方案20】:

                      另一种方法是,如果你有 httpclient.jar 文件,那么你可以这样做 这个:

                      将 .jar 文件粘贴到项目的“libs 文件夹”中。然后在 gradle 中在你的 build.gradle(Module:app) 中添加这一行

                      dependencies {
                      compile fileTree(include: ['*.jar'], dir: 'libs')
                      compile 'com.android.support:appcompat-v7:23.0.0'
                      compile files('libs/httpcore-4.3.3.jar')
                      }
                      

                      【讨论】:

                        【解决方案21】:

                        自 2021 年 4 月起,您可以使用以下产品:

                        在您的应用程序 gradle 中,在 'dependencies { ' 下添加以下内容:

                        implementation 'org.apache.httpcomponents:httpcore:4.4.10'
                        implementation 'org.apache.httpcomponents:httpclient:4.5.6'
                        

                        在您的 Java 活动中,添加以下导入:

                        import org.apache.http.client.HttpClient;
                        

                        然后您应该能够将 HttpClient 添加到您的方法中。

                        【讨论】:

                          【解决方案22】:

                          错误:(30, 0) Gradle DSL 方法未找到:'classpath()' 可能的原因:

                        • 项目“cid”可能正在使用不包含该方法的 Android Gradle 插件版本(例如,在 1.1.0 中添加了“testCompile”)。 将插件升级到 2.3.3 版本并同步项目
                        • 项目“cid”可能正在使用不包含该方法的 Gradle 版本。 打开 Gradle 包装文件
                        • 构建文件可能缺少 Gradle 插件。 应用 Gradle 插件
                        • 【讨论】:

                            【解决方案23】:

                            适用于 Android API 28 及更高版本 在应用标签内的 Manifest.xml 中

                                <application
                                .
                                .
                                .
                            
                                <uses-library android:name="org.apache.http.legacy" android:required="false"/>
                            

                            【讨论】:

                              【解决方案24】:

                              我认为根据您拥有的 Android Studio 版本,更新您的 android studio 也很重要,我也很沮丧,听从了大家的建议,但没有运气,直到我不得不将我的 android 版本从 1.3 升级到 1.5,错误像魔术一样消失了。

                              【讨论】:

                                猜你喜欢
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 2019-02-20
                                • 2017-06-28
                                • 1970-01-01
                                • 1970-01-01
                                相关资源
                                最近更新 更多