HttpClient赢得';Android Studio中的导入

HttpClient赢得';Android Studio中的导入,android,gradle,android-gradle-plugin,apache-httpclient-4.x,Android,Gradle,Android Gradle Plugin,Apache Httpclient 4.x,我在Android Studio中编写了一个简单的类: package com.mysite.myapp; import org.apache.http.client.HttpClient; public class Whatever { public void headBangingAgainstTheWallExample () { HttpClient client = new DefaultHttpClient(); } } 由此我得到以下编译时错误

我在Android Studio中编写了一个简单的类:

package com.mysite.myapp;

import org.apache.http.client.HttpClient;

public class Whatever {
    public void headBangingAgainstTheWallExample () {
        HttpClient client = new DefaultHttpClient();
    }
}
由此我得到以下编译时错误:

无法解析符号HttpClient

Android Studio SDK中不包括
HttpClient
?即使不是,我也将其添加到Gradle构建中,如下所示:

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

无论是否有最后一个编译行,错误都是相同的。我缺少什么?

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


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

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

您也可以尝试下载并直接包含到您的项目中,或者改用项目中的哪个API目标?
AndroidHttpClient
仅适用于API级别8ApacheHttp客户端在v23 sdk中被删除。您可以使用HttpURLConnection或第三方Http客户端,如OkHttp


参考:
https://developer.android.com/preview/behavior-changes.html#behavior-ApacheHTTP客户端在API级别22中被弃用,在API级别23中被删除。如果必须的话,您仍然可以在API级别23及以后的版本中使用它,但是最好转到支持的方法来处理HTTP。因此,如果您使用23进行编译,请在build.gradle中添加以下内容:

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

1-从以下位置下载Apache jar文件(截至此答案)4.5.zip文件:

2-打开zip,将jar文件复制到您的libs文件夹中。你可以找到它,如果你去你的项目顶部,上面写着“Android”,你会发现一个列表,当你点击它。所以

Android->Project->app->libs

,然后把罐子放在那里

3-内置.gradle(模块:应用程序)添加

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;

要将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 {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}
Android studio关于gradle更新的通知:

特定于模块的build.gradle-/app/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 {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

在API 22中,它们被弃用,在API 23中,它们被完全删除。如果您不需要新添加的所有花哨内容,一个简单的解决方法是简单地使用apache中的.jar文件,这些文件在API 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

您只需将其添加到渐变依赖项:

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

TejaDroid在下面链接中的回答帮助了我

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

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

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

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
Android 6.0(API级别23)版本取消了对Apache HTTP客户端的支持。因此,您不能在API 23中直接使用此库。但是有一种方法可以使用它。在build.gradle文件中添加useLibrary“org.apache.http.legacy”,如下所示-

android {
    useLibrary 'org.apache.http.legacy'
}
如果这不起作用,您可以应用以下黑客-

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

–现在在build.gradle文件的依赖项{}部分添加编译文件('libs/org.apache.http.legacy.jar')。

只需使用以下命令:-

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

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

android {
    useLibrary 'org.apache.http.legacy'
    .
    .
    .
并在依赖项中添加以下代码段:

//web服务的http最终解决方案(包括文件上载)


它还将帮助您使用多功能上传文件

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

sdk 23和23+中不支持HttpClient

如果您需要在sdk 23中使用,请在gradle中添加以下代码:

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

这对我有用。希望对您有用。

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

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

将这两行添加到dependencies下

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


在android下,您只需添加一行

useLibrary 'org.apache.http.legacy'
例如,进入build.gradle(模块: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'
}

如前所述,
org.apache.http.client.HttpClient
在以下情况下不再受支持:

SDK(API级)#23

您必须使用
java.net.HttpURLConnection

如果您想在使用
HttpURLConnection
时简化代码(和生活),这里有一个此类的
Wrapper
,它可以让您使用
JSON
执行
GET
POST
PUT
的简单操作,例如,执行
httpput

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

}
package com.calculistik.repository;
导入java.io.BufferedReader;
导入java.io.BufferedWriter;
导入java.io.ByteArrayOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.io.OutputStreamWriter;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.HashMap;
导入java.util.Map;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
/**
*请勿更改或删除版权声明或此标题。
*
*版权所有©2017,Calculistik。版权所有。
*
*Oracle和Java是Oracle和/或其子公司的注册商标
*附属公司。其他名称可能是其各自所有者的商标。
*
*本文件的内容受GNU或
*仅通用公共许可证版本2(“GPL”)或通用
*开发和分销许可证(“CDDL”)(统称为
*“许可证”)。你不能用这个
    <application
    .
    .
    .

    <uses-library android:name="org.apache.http.legacy" android:required="false"/>
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
implementation 'org.apache.httpcomponents:httpclient:4.5.6'
import org.apache.http.client.HttpClient;