我正在使用
android studio创建一个向服务器发出GET请求的应用程序.我的代码是这样的:
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;
}
}
}
问题是Android Studio标记了这一行
client.execute(get);
有错误:
说“无法访问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'
}
解决方法
在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();