285

Tôi có một lớp đơn giản bằng văn bản trong Android Studio:HttpClient sẽ không nhập khẩu trong Android Studio

package com.mysite.myapp; 

import org.apache.http.client.HttpClient; 

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

và từ nay tôi nhận được lỗi thời gian biên dịch sau:

ISN' t HttpClient được bao gồm trong SDK Android Studio? Ngay cả khi nó không phải là, tôi thêm nó vào Gradle của tôi xây dựng như thế này:

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

Có hoặc không có dòng biên dịch cuối cùng, lỗi là như nhau. Tôi đang thiếu gì?

+3

Hãy thử sử dụng 'AndroidHttpClient' nếu bạn có thể. HttpClient stubs thực sự chứa bên trong jar android, do đó, không cần phải tham chiếu đến nó một cách rõ ràng. Lưu ý rằng phiên bản android của httpclient có lẽ là 4.1.1. Việc cố gắng sử dụng phiên bản mới hơn trên đầu trang thường gây ra sự cố (đọc: không hoạt động, vì trình nạp lớp chương trình cơ sở luôn thắng). – dhke

Trả lời

687

HttpClient không được hỗ trợ nữa trong sdk 23. Bạn phải sử dụng URLConnection hoặc hạ cấp xuống SDK 22 (compile 'com.android.support:appcompat-v7:22.2.0')

Nếu bạn cần sdk 23, thêm video này vào gradle của bạn:

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

Bạn cũng có thể thử tải xuống và bao gồm HttpClient jar trực tiếp vào dự án của mình hoặc sử dụng OkHttp thay vì

+3

Liên kết thông báo: https://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client – dhke

+18

Nó không làm gì trong trường hợp của tôi. Làm thế nào mà? –

+2

useLibrary không thể được giải quyết khi tôi thêm nó. Mục tiêu của tôi là 23, những gì tôi đang thiếu? – fullMoon

3

Mục tiêu API nào bạn có trong dự án của mình? AndroidHttpClient chỉ dành cho API Cấp 8 <. và xin vui lòng có một cái nhìn vào here

thưởng thức mã của bạn :)

5

ApacheHttp Khách hàng được lấy ra trong v23 sdk. Bạn có thể sử dụng HttpURLConnection hoặc ứng dụng khách của bên thứ ba như OkHttp.

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

+0

Việc sử dụng 'HttpUrlConnection' thực sự được khuyến khích thay cho HttpClient –

140

HttpClient đã bị phản đối trong API Level 22 và loại bỏ trong API Cấp 23. Bạn vẫn có thể sử dụng nó trong API Level 23 trở đi nếu bạn phải, tuy nhiên nó là tốt nhất để di chuyển đến các phương pháp hỗ trợ để xử lý HTTP. Vì vậy, nếu bạn đang biên soạn với 23, thêm này trong build.gradle của bạn:

file
android { 
    useLibrary 'org.apache.http.legacy' 
} 
+1

Đây phải là câu trả lời được chấp nhận. –

+1

giải pháp dễ dàng và nhanh chóng nếu ai đó không ngại sử dụng một lớp không được chấp nhận ... – prom85

+4

'android { useLibrary 'org.apache.http.legacy' }' ** [khi bạn thêm điều này] ** ** [ 1] ** 'android. studio' org.apache.http 'vẫn có mẹo:' Không thể phân giải biểu tượng ' ** [2] ** điều này làm cho android-studio (với sdk23) có thể tạo. mặc dù có lời khuyên (Không thể giải quyết biểu tượng) ** [3] ** nếu bạn thêm jar, không có mẹo nào, nhưng không thể chạy, vì nó có hai bản sao 'org.apache.http' – YETI

15

1- tải Apache jar (tính đến câu trả lời này) tập tin 4.5.zip từ:
https://hc.apache.org/downloads.cgi?Preferred=http%3A%2F%2Fapache.arvixe.com%2F

2- mở zip sao chép các tập tin jar vào thư mục libs của bạn. Bạn có thể tìm thấy nó nếu bạn đi đến đỉnh của dự án của bạn, nơi nó nói "Android" bạn sẽ tìm thấy một danh sách khi bạn nhấp vào nó. Vì vậy,

Android -> Project -> app -> libs

, Sau đó đặt lọ ở đó.

3- Đang xây dựng.grale (Mudule: ứng dụng) thêm

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

trong

dependency { 
    } 

4- Trong lớp java thêm các hàng nhập khẩu:

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

Để sử dụng Apache HTTP cho SDK Cấp 23:

Cấp cao nhất 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/ 
    } 
    ... 
} 

Thông báo từ Android studio về bản cập nhật gradle:

Notification from Android studio about gradle update

Mô-đun cụ thể build.gradle - /app/build.gradle

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

Chỉ điều này làm việc cho tôi, cảm ơn! – Roman

6

trong API 22 họ trở nên bị phản đối và trong API 23, họ đã xóa hoàn toàn, một cách giải quyết đơn giản nếu bạn không cần tất cả những nội dung ưa thích từ các phần bổ sung mới chỉ đơn giản là sử dụng file .jar từ apache đã được tích hợp trước khi API 22, nhưng khi tách ra .jar file:

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 
4

Bạn chỉ có thể thêm video này vào Gradle phụ thuộc: câu trả lời

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

Điều này giúp ích. Nhưng vẫn chưa đủ nếu bạn muốn sử dụng các lớp khác như 'HttpGet'. Đối với điều đó tôi đã sử dụng 'compile 'org.jbundle.util.osgi.wrapped: org.jbundle.util.osgi.wrapped.org.apache.http.client: 4.1.2'' – AlexAndro

50

TejaDroid tại liên kết dưới đây giúp tôi. 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' 
    ... 
} 
+0

làm việc cho tôi quá –

+0

cảm ơn đây là chỉ giải pháp làm việc với các eperimental mới xây dựng như useLibrary không được công nhận trong nó – pt123

+0

thankz.It làm việc cho tôi –

2

Another way is if you have httpclient.jar file then you can do this :

Dán file .jar của bạn trong "thư mục libs" trong dự án của bạn. Sau đó, trong gradle thêm dòng này trong build.gradle của bạn (Học phần: ứng dụng)

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

Hãy thử điều này làm việc cho tôi Thêm sự phụ thuộc này để build.gradle tập tin của bạn

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

Cảm ơn, Bạn đã cứu mạng tôi. :) –

5

Android 6.0 (API Cấp 23) loại bỏ hỗ trợ cho máy khách HTTP Apache. Do đó bạn không thể sử dụng thư viện này trực tiếp trong API 23. Nhưng có một cách để sử dụng nó. Thêm useLibrary 'org.apache.http.legacy' trong tập tin build.gradle của bạn như liệt kê dưới đây

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

Nếu điều này không làm việc bạn có thể áp dụng các hack-

sau - Sao chép org.apache.http .legacy.jar nằm trong/platform/android-23/đường dẫn tùy chọn của thư mục SDK Android của bạn vào thư mục app/libs của dự án của bạn.

- Bây giờ, hãy thêm tệp biên dịch (‘libs/org.apache.http.legacy.jar’) vào phần phụ thuộc {} của tệp build.gradle.

+0

Tùy chọn cuối cùng bạn đã thực hiện tốt. Tôi đánh giá cao. –

4

Đơn giản chỉ cần sử dụng này: -

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

HttpClient không được hỗ trợ nữa trong sdk 23. Android 6.0 (API Level 23) phát hành loại bỏ hỗ trợ cho khách hàng Apache HTTP. Bạn phải sử dụng

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

và cũng thêm bên dưới đoạn mã trong sự phụ thuộc của bạn:

// http giải pháp cuối cùng cho web-dịch vụ (bao gồm cả tập tin tải lên)

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

Nó cũng sẽ giúp bạn trong khi bạn sử dụng Sử dụng MultipartEntity cho Tải lên tệp.

+0

Điều này làm việc cho mee –

+0

Vui mừng khi biết rằng nó giúp bạn :) –

+0

Tôi có vấn đề với điều đó ... trùng lặp mục nhập: org/apache/http/HttpHeaders.class. Bạn có biết vấn đề là gì không? – DaniG

-1

Tôi nghĩ tùy thuộc vào phiên bản Android Studio nào, bạn cũng cần cập nhật studio android của mình, tôi đã trở nên thất vọng sau lời khuyên của mọi người nhưng không may mắn, cho đến khi tôi phải nâng cấp phiên bản Android của mình từ 1,3 lên 1,5, các lỗi biến mất như ma thuật.

4

HttpClient không được hỗ trợ trong sdk 23 và 23+.

Nếu bạn cần phải sử dụng thành sdk 23, thêm bên dưới mã để gradle của bạn:

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

của nó làm việc cho tôi. Hy vọng hữu ích cho bạn.

+0

Làm việc hoàn hảo với phiên bản SDK 24 –

4

Nếu bạn cần sdk 23, thêm video này vào gradle của bạn:

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

Thêm hai dòng sau dưới phụ thuộc

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

sau đó

useLibrary 'org.apache.http.legacy' 

dưới android

4

Bạn phải thêm chỉ là một dòng

useLibrary 'org.apache.http.legacy' 

vào build.gradle (Học phần: ứng dụng), ví dụ

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' 
} 
2

Như đã đề cập trước đó, org.apache.http.client.HttpClient không được hỗ trợ bất kỳ trong hơn:

SDK (cấp API) # 23.

Bạn phải sử dụng java.net.HttpURLConnection.

Nếu bạn muốn làm cho mã của bạn (và cuộc sống) dễ dàng hơn khi sử dụng HttpURLConnection, đây là một Wrapper của lớp này sẽ cho phép bạn làm thao tác đơn giản với GET, POSTPUT sử dụng JSON, ví dụ như, làm một 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() 

Hãy sử dụng nó.

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

} 
+0

cảm ơn, công việc tuyệt vời! – KGCybeX

0

Lỗi: (30, 0) Gradle phương pháp DSL không tìm thấy: 'classpath()' Nguyên nhân có thể:

  • Dự án 'CID' có thể được sử dụng một phiên bản của Android Gradle plug-in mà không chứa phương thức (ví dụ 'testCompile' đã được thêm vào trong 1.1.0). Nâng cấp plugin lên phiên bản 2.3.3 và đồng bộ hóa dự án
  • Dự án 'cid' có thể đang sử dụng phiên bản Gradle không chứa phương pháp. Mở tệp trình bao bọc Gradle
  • Tệp xây dựng có thể thiếu plugin Gradle. Áp dụng plugin Gradle
  • Các vấn đề liên quan