Android Studio中无法解析符号HttpGet、HttpClient、HttpResponse。

55

我只是复制了所有Http的jar文件,但Android Studio无法导入所有这些jar文件。它会给出一个错误:Cannot resolve symbol HttpGet, HttpClient, HttpResponse

我的Activity文件在这里:

public class MainActivity extends AppCompatActivity {

ArrayList<Product>  productslist;
ProductAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    productslist = new ArrayList<Product>();
    new JSONAsyncTask().execute("http://opencart.codeniques.com/myshop/?route=feed/web_api/products&id=60&key=test123");

    ListView listView = (ListView)findViewById(R.id.list);
    adapter = new ProductAdapter(getApplicationContext(),R.layout.row,productslist);

    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getApplicationContext(),productslist.get(position).getName(),Toast.LENGTH_LONG).show();
        }
    });
}

class JSONAsyncTask extends AsyncTask<String,Void,Boolean>{

    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Loading, please wait");
        dialog.setTitle("Connecting server");
        dialog.show();
        dialog.setCancelable(false);
    }

    @Override
    protected Boolean doInBackground(String... params) {
        try{
            HttpGet httppost = new HttpGet(params[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            int status = response.getStatusLine().getStatusCode();

            if(status == 200){
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);

                JSONObject jsono = new JSONObject(data);
                JSONArray jarray = jsono.getJSONArray("products");

                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject object = jarray.getJSONObject(i);

                    Product actor = new Product();

                    actor.setId(object.getString("id"));
                    actor.setName(object.getString("name"));
                    actor.setDescription(object.getString("description"));
                    actor.setHref(object.getString("href"));
                    actor.setPrice(object.getString("pirce"));
                    actor.setImage(object.getString("thumb"));
                    actor.setSpecial(object.getString("special"));
                    actor.setRating(object.getString("rating"));

                    productslist.add(actor);
            }
                return  true;
            }
        }catch (JSONException e){
            Log.e("Error :",e.getMessage());
        }catch (ParseException e){
            Log.e("Error :",e.getMessage());
        }catch (IOException e){
            Log.e("Error :",e.getMessage());
        }catch (Exception e){
            Log.e("Error :",e.getMessage());
        }
        return  false;
    }
    @Override
    protected void onPostExecute(Boolean aBoolean) {
        dialog.cancel();
        adapter.notifyDataSetChanged();
        if(aBoolean == false){
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
        }
    }
}}

这里是我的gradle

apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "22.0.1"

defaultConfig {
    applicationId "android.catalyst.com.newjsonarray"
    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'])

testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'}

1
请使用HttpUrlConnection而不是HttpClient。请查看链接Link - Irfan
据我所知,Apache Http客户端在Marshmallow中不再受支持。开始使用Retrofit。 - Jolson Da Costa
1
@Skynet HttpClient 并没有被弃用,它在 api 23 中被移除了。 - Gabriele Mariotti
1
我使用了这个教程:http://www.blazin.in/2016/03/http-connection-for-android-marshmallow.html - Bhushan Shirsath
此外,如果您的目标是SDK 28+,那么也请阅读这篇文章 - Kathir
显示剩余2条评论
12个回答

105

只需在您的依赖项中添加这个即可

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

最后

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])    
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
}

还要添加这段代码:

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

更多信息请参见文档中的指定Apache HTTP Legacy库的要求

If your app is targeting API level 28 (Android 9.0) or above, you must include the following declaration within the element of AndroidManifest.xml.

 <uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />

2
部分工作。 我尝试了同样的方法,这样就可以访问一些类 - HttpEntity、BufferedHttpEntity以及HttpResponse。 但是,仍然无法访问HttpClient、HttpGet和DefaultHttpClient。 - Narendra Singh
1
@IntelliJAmiya使用了org.apache.http.legacy库,但HttpGet、HttpClient和DefaultHttpClient已经被弃用。 - Shruti
1
@Shruti姐,是的。请查看https://dev59.com/IGUp5IYBdhLWcg3wVWmv - IntelliJ Amiya
1
@IntelliJAmiya 当然,我会检查。感谢您的快速回复! - Shruti
1
@Shruti 这是我的职责,女士。谢谢。 - IntelliJ Amiya
显示剩余4条评论

38

HttpClient在sdk 23中不再受支持。您必须使用URLConnection或降级到sdk 22(编译'com.android.support:appcompat-v7:22.2.0')。

如果您需要sdk 23,请将此添加到gradle:

在依赖项中添加:

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

还需要添加这个

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

12
еҸӘйңҖиҰҒдҪҝз”ЁuseLibrary 'org.apache.http.legacy'е°ұи¶ід»Ҙи§ЈеҶіиҝҷдёӘй—®йўҳпјҢе…¶д»–еә“жҳҜдёҚеҝ…иҰҒзҡ„пјҲиҮіе°‘еңЁжҲ‘зҡ„жғ…еҶөдёӢжҳҜиҝҷж ·пјүгҖӮ - Franco

14

HttpClient在API Level 22中已被废弃并在API Level 23中被移除。 你必须使用URLConnection


9
请将以下代码添加到您的依赖项中。它会起作用。
implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:23.1.0'
    implementation 'com.android.support:design:23.1.0'
    implementation 'com.android.support:cardview-v7:23.1.0'
    implementation 'com.android.support:recyclerview-v7:23.1.0'

    implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}

4

请删除libs文件夹中的所有Http jar文件,并在gradle文件中添加以下依赖项:

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

谢谢。

@Anand Jain:如果我漏掉了任何库,请添加! - AndiGeeky

1

对我而言,以下内容有所帮助

找到 org.apache.http.legacy.jar,它在 Android/Sdk/platforms/android-23/optional 中,将其添加到您的依赖项中。

来源


1

Google官方建议开发者在网络相关的事务中使用Volley库(这里),所以现在是时候转向Volley了。祝编码愉快!


1
只需在您的build.gradle文件中添加此行代码,它就可以正常工作。
implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

如果上述方法无效,请添加以下行。
compile 'com.google.android.gms:play-services:+'
compile ('org.apache.httpcomponents:httpmime:4.2.6'){
    exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient:4.2.6'

compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'

1
请在'libs'文件夹中删除所有Http的jar文件,并在gradle文件中添加以下依赖项:
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpcore:4.4.3'

or

useLibrary 'org.apache.http.legacy'

0

加上这个对我有用。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接