HttpClient는 Android Studio에서 가져 오지 않습니다.
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'
}
마지막 컴파일 라인의 유무에 관계없이 오류는 동일합니다. 내가 무엇을 놓치고 있습니까?
HttpClient
SDK 23에서 더 이상 지원되지 않습니다. URLConnection
SDK 22 ( compile 'com.android.support:appcompat-v7:22.2.0'
) 로 사용 하거나 다운 그레이드해야합니다.
SDK 23이 필요하면 이것을 gradle에 추가하십시오.
android {
useLibrary 'org.apache.http.legacy'
}
HttpClient jar 을 다운로드 하여 프로젝트에 직접 포함 시키거나 OkHttp를 대신 사용할 수도 있습니다.
HttpClient는 API 레벨 22에서 더 이상 사용되지 않고 API 레벨 23에서 제거되었습니다. 필요한 경우 API 레벨 23 이상에서 계속 사용할 수 있지만 지원되는 메소드로 이동하여 HTTP를 처리하는 것이 가장 좋습니다. 따라서 23으로 컴파일하는 경우 build.gradle에 이것을 추가하십시오.
android {
useLibrary 'org.apache.http.legacy'
}
아래 링크에서 TejaDroid의 답변이 도움이되었습니다. Android Studio에서 org.apache.http.HttpResponse를 가져올 수 없습니다
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'
...
}
SDK 레벨 23에 Apache HTTP를 사용하려면 다음을 수행하십시오.
최상위 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/
}
...
}
gradle 업데이트에 대한 Android Studio의 알림 :
모듈 별 build.gradle-/app/build.gradle
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
...
useLibrary 'org.apache.http.legacy'
...
}
이것을 시도해보십시오. build.gradle 파일 에이 종속성을 추가하십시오
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
1-Apache jar 파일 (이 답변 기준) 4.5.zip 파일 :
https://hc.apache.org/downloads.cgi?Preferred=http%3A%2F%2Fapache.arvixe.com%2F
2- zip 파일을 열어 jar 파일을 libs 폴더에 복사하십시오. 프로젝트 상단으로 이동하면 "Android"라고 표시되며 클릭하면 목록을 찾을 수 있습니다. 그래서,
안드로이드-> 프로젝트-> 앱-> libs
그런 다음 항아리를 넣으십시오.
3- build.gradle (모듈 : 앱) 추가
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;
SDK 23에서는 HttpClient가 더 이상 지원되지 않습니다. Android 6.0 (API 레벨 23) 릴리스는 Apache HTTP 클라이언트에 대한 지원을 제거합니다. 당신은 사용해야합니다
android {
useLibrary 'org.apache.http.legacy'
.
.
.
또한 종속성에 아래 코드 스 니펫을 추가하십시오.
// 웹 서비스 용 최종 솔루션 (파일 업로드 포함)
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
당신이 사용 사용하는 동안 그것은 또한 당신을 도울 것입니다 MultipartEntity를 위한 파일 업로드 .
API 22에서는 더 이상 사용되지 않으며 API 23에서는 완전히 제거되었습니다. 새로운 추가 기능에서 멋진 모든 것을 필요로하지 않는 경우 간단한 해결 방법은 API 22 이전에 통합 된 아파치의 .jar 파일을 단순히 사용하는 것입니다. 분리 된 .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
Gradle 의존성에 이것을 간단히 추가 할 수 있습니다.
compile "org.apache.httpcomponents:httpcore:4.3.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 / optional 경로에있는 org.apache.http.legacy.jar을 프로젝트의 app / libs 폴더로 복사하십시오.
– 이제 build.gradle 파일의 dependencies {} 섹션 안에 컴파일 파일 ( 'libs / org.apache.http.legacy.jar')을 추가하십시오.
다음과 같은 클래스를 가져 오려면
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)
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'
}
ApacheHttp 클라이언트는 v23 SDK에서 제거되었습니다. HttpURLConnection 또는 OkHttp와 같은 타사 Http Client를 사용할 수 있습니다.
심판 : https://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client
간단히 이것을 사용하십시오 :-
android {
.
.
.
useLibrary 'org.apache.http.legacy'
.
.
.
}
HttpClient는 SDK 23 및 23 이상에서 지원되지 않습니다.
SDK 23에 사용해야하는 경우 아래 코드를 gradle에 추가하십시오.
android {
useLibrary 'org.apache.http.legacy'
}
그것은 나를 위해 일하고 있습니다. 당신에게 유용한 희망.
SDK 23이 필요하면 이것을 gradle에 추가하십시오.
android {
useLibrary 'org.apache.http.legacy'
}
한 줄만 추가하면됩니다
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'
}
프로젝트 내에 어떤 API 타겟이 있습니까? AndroidHttpClient
API 레벨 8에만 해당됩니다. 여기 좀 봐주세요
코드를 즐기십시오 :)
앞에서 언급했듯이 org.apache.http.client.HttpClient
더 이상 지원되지 않습니다.
SDK (API 레벨) # 23.
을 사용해야 java.net.HttpURLConnection
합니다.
당신이 사용하는 경우 코드 (삶)을 쉽게 확인하려면 HttpURLConnection
, 여기입니다 Wrapper
당신은 간단한 작업을 할 수있게된다이 클래스의 GET
, POST
및 PUT
사용 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;
}
}
이 두 줄을 종속성 아래에 추가하십시오.
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
그때
useLibrary 'org.apache.http.legacy'
안드로이드에서
또 다른 방법은 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')
}
오류 : (30, 0) Gradle DSL 메서드를 찾을 수 없음 : 'classpath ()'가능한 원인 :
나는 당신이 가지고있는 안드로이드 스튜디오 버전에 따라 안드로이드 스튜디오도 업데이트하는 것이 중요하다고 생각합니다. 모든 사람들의 조언에 따라 좌절감을 느끼고 있지만 운이 없습니다. 안드로이드 버전을 1.3에서 1.5로 업그레이드해야 할 때까지 오류는 사라졌습니다. 마법.
참고 URL : https://stackoverflow.com/questions/32153318/httpclient-wont-import-in-android-studio
'Programing' 카테고리의 다른 글
pandas GroupBy를 사용하여 각 그룹 (예 : 개수, 평균 등)에 대한 통계를 얻으십니까? (0) | 2020.03.02 |
---|---|
jQuery 유효성 검사 : 기본 오류 메시지 변경 (0) | 2020.03.02 |
Objective-C에서 NSArray를 어떻게 되돌릴 수 있습니까? (0) | 2020.03.02 |
jQuery-여러 $ (문서) .ready…? (0) | 2020.03.02 |
.NET에서 CultureInfo의 CurrentCulture 속성과 CurrentUICulture 속성의 차이점은 무엇입니까? (0) | 2020.03.02 |