Android-HttpClient-Get请求获取网络图片设置壁纸

第一种方式使用httpclient-*.jar (需要在网上去下载httpclient-*.jar包)

把httpclient-4.5.jar/httpclient-4.4.1.jar包放入到libs里,然后点击sync project ...才能使用httpclient-4.5.jar包

httpclient-4.5.jar不好用,建议使用httpclient-4.4.1.jar

第二种方式:配置AndroidStudio 的方式获取 HttpClient

在相应的module下的build.gradle中加入:useLibrary 'org.apache.http.legacy'

这条语句一定要加在 android{ } 当中,然后rebulid

例如:


 app/build.gradle android { useLibrary 'org.apache.http.legacy' }

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "liudeli.async"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    useLibrary 'org.apache.http.legacy'
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

在AndroidManifest.xml加入权限:

  <!-- 访问网络是危险的行为 所以需要权限 -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- 设置壁纸是危险的行为 所以需要权限 -->
    <uses-permission android:name="android.permission.SET_WALLPAPER" />

 MainActivity5:

package liudeli.async;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

public class MainActivity5 extends Activity {

    private final static String TAG = MainActivity5.class.getSimpleName();

    // 图片地址
    private final String PATH = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000" +
            "&sec=1544714792699&di=3c2de372608ed6323f583f1c1b445e51&imgtype=0&src=http%3A%2F%2Fp" +
            "2.qhimgs4.com%2Ft0105d27180a686e91f.jpg";

    private ImageView imageView;
    private Button bt_set_wallpaper;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main4);

        imageView = findViewById(R.id.iv_image);
        bt_set_wallpaper = findViewById(R.id.bt_set_wallpaper);

        Button bt_get_image = findViewById(R.id.bt_get_image);
        bt_get_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 让异步任务执行耗时操作
                new DownloadImage().execute(PATH);
            }
        });

        bt_set_wallpaper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != bitmap) {
                    try {
                        setWallpaper(bitmap);
                        Toast.makeText(MainActivity5.this, "壁纸设置成功", Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(MainActivity5.this, "壁纸设置失败", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

    private Bitmap bitmap;

    class DownloadImage extends AsyncTask<String, Void, Object> {

        /**
         * 执行耗时操作前执行
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // 弹出进度条
            progressDialog = new ProgressDialog(MainActivity5.this);
            progressDialog.setMessage("Download ...");
            progressDialog.show();
        }

        /**
         * 执行耗时操作
         * @param strings
         * @return
         */
        @Override
        protected Object doInBackground(String... strings) {
            try {

                /**
                 * 第一步
                 * HttpClient是接口 不能直接实例化,需要通过HttpClient接口的子类 DefaultHttpClient来实例化
                 */
                HttpClient httpClient = new DefaultHttpClient();

                /**
                 * 第三步
                 * 实例化HttpGet对象,Get请求方式,应该说是请求对象
                 */
                HttpUriRequest getRequest = new HttpGet(PATH);

                /**
                 * 第二步
                 * 执行任务
                 */
                HttpResponse response = httpClient.execute(getRequest);

                /**
                 * 第四步
                 * 判断请求码 是否请求成功
                 */
                int responseCode = response.getStatusLine().getStatusCode();
                Log.d(TAG, "responseCode:" + responseCode);
                if (HttpURLConnection.HTTP_OK == responseCode) {
                    /**
                     * 第五步
                     * 获取到服务区响应的字节流数据 然后转换成图片Bitmap数据
                     */
                    InputStream inputStream = response.getEntity().getContent();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 耗时执行过程中 更新进度条刻度操作
         * @param values
         */
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        /**
         * 耗时操作执行完成,用于更新UI
         * @param o
         */
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

            if (o != null) { // 成功
                bitmap = (Bitmap) o;

                // 故意放慢两秒,模仿网络差的效果
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 设置从网上下载的图片
                        imageView.setImageBitmap(bitmap);
                        // 设置为可以点击
                        bt_set_wallpaper.setEnabled(true);

                        // 关闭进度条
                        progressDialog.dismiss();
                    }
                }, 2000);
            } else { //失败
                bt_set_wallpaper.setEnabled(false);
                Toast.makeText(MainActivity5.this, "下载失败,请检查原因", Toast.LENGTH_LONG).show();
                // 关闭进度条
                progressDialog.dismiss();
            }
        }
    }
}

activity_layout5.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/bt_get_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取图片"
        android:onClick="getImage"
        android:layout_marginLeft="20dp"
        />

    <Button
        android:id="@+id/bt_set_wallpaper"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="设置壁纸"
        android:layout_alignParentRight="true"
        android:layout_marginRight="20dp"
        android:enabled="false"
        />

    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/bt_get_image" />


</RelativeLayout>

操作结果:

猜你喜欢

转载自www.cnblogs.com/android-deli/p/10247469.html