Android 无法访问 org.apache.http.client.HttpClient [英] Android Cannot access org.apache.http.client.HttpClient

查看:77
本文介绍了Android 无法访问 org.apache.http.client.HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 android studio 创建一个向服务器发出 GET 请求的应用程序.我的代码是这样的:

I'm using android studio to create an app that makes a GET request to a server. My code is this:

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 标记了线

The problem is that Android Studio marks the line

client.execute(get);

有错误:

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

saying "Cannot access org.apache.http.client.HttpClient"

这是我的 gradle 文件:

Here's my gradle file:

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 中

In Android SDK 23

HttpClient 已被弃用,因为它推断,您可以在 HttpURLConnection

HttpClient is deprecated because it inference, you can migrate your code in HttpURLConnection

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

你可以使用这个,但不再推荐使用

You can use this, but it's not recommended anymore

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();

这篇关于Android 无法访问 org.apache.http.client.HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆