2015-10-06 74 views
5

我正在使用android studio创建一个应用程序,它向服务器发出GET请求。我的代码是这样的:Android无法访问org.apache.http.client.HttpClient

import org.apache.http.client.methods.CloseableHttpResponse; 
import org.apache.http.client.methods.HttpGetHC4; 
import org.apache.http.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClientBuilder; 

public class HTTPHelper 
{ 
    private String base; 

    public HTTPHelper (String base) 
    { 
     this.base = base; 
    } 

    public String doGet (String path) 
    { 
     try 
     { 
      CloseableHttpClient client = HttpClientBuilder.create().build(); 
      HttpGetHC4 get = new HttpGetHC4(path); 
      CloseableHttpResponse response = client.execute(get); 

      return ""; 
     } 
     catch (Exception e) 
     { 
      return null; 
     } 
    } 
} 

的proiblem是Android的工作室,标志着线

client.execute(get); 

一个错误:

enter image description here

说“无法访问org.apache.http .client.HttpClient“

这是我的gradle文件:

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 23 
    buildToolsVersion "23.0.0" 

    defaultConfig { 
     applicationId "principal.halloween" 
     minSdkVersion 16 
     targetSdkVersion 23 
     versionCode 1 
     versionName "1.0" 
    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    compile 'com.android.support:appcompat-v7:23.0.0' 
    compile 'com.pubnub:pubnub-android:3.7.5' 
    compile 'com.google.code.gson:gson:2.3.1' 
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1' 
    compile 'org.apache.httpcomponents:httpclient:4.3.6' 

} 
+0

你试过用requestBuilder吗?它的设置比你有一点差异。首先,可能在客户端构建器中出现错误,这与RequestBuilder.build的情况不同,后面是“执行”http://www.baeldung.com/httpclient-custom-http-header re:第4部分 –

回答

-1

这是因为现在sdk 23中不支持HttpClient。尝试在你的Gradle中添加这个 。

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

如果这不起作用,只需下载HttpClient jar文件并添加到您的库。

如果仍然无效,您必须将您的compileSdkVersion降级到22或更低。

+0

。你不会下载HttpClient导致无法工作,你需要下载httpclient-android。 编译组: 'org.apache.httpcomponents',名称: 'HttpClient的-机器人',版本: '4.3.5.1' 编译( 'org.apache.httpcomponents:httpmime:4.3.6'){ 排除模块:'httpclient' } –

4

在Android SDK中23

HttpClient的是反对,因为它的推论,你可以在HttpURLConnection

https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client

您可以使用此迁移你的代码,但它不建议再

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

对于HttpURLConnection

URL url = new URL(urlString); 
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
connection.setRequestMethod("GET"); 
connection.setDoInput(true); 
connection.connect();