第一种方式使用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>

操作结果:

Android-HttpClient-Get请求获取网络图片设置壁纸的更多相关文章

  1. HttpClient get请求获取数据流

    HttpClient get请求获取数据流,将数据保存为文件 public String getStreamFile(String url) throws Exception { HttpClient ...

  2. Android-获取网络图片设置壁纸

    下载图片,设置壁纸 的代码: package liudeli.async; import android.app.Activity; import android.app.ProgressDialog ...

  3. [转]Android 如何根据网络地址获取网络图片方法

    http://blog.csdn.net/xiazdong/article/details/7724103 目录(?)[-] h2pre namecode classhtml stylefont-we ...

  4. Android学习笔记进阶21之设置壁纸

    别忘记在ApplicationManifest.xml 中加上权限的设置. <uses-permission Android:name = "android.permission.SE ...

  5. HTTPclient cookie的获取与设置

    因为代码与Java用apache的HttpClient发送Post请求大部份重复,所以就不贴整段代码了,只把不同的地方贴出来.发送Cookie就必须先得到Cookie,所以至少发送两次请求,第一次用于 ...

  6. Android学习八:获取网络图片

    看到QQ群里有个朋友说加载图片内存溢出的问题,所以就按照自己的想法试试的.但是按照他的方法,不知道为何没有发生内存溢出,不知道什么情况. 写这篇文章主要有三个目的: 1.多线程的学习 2.图片加载的学 ...

  7. 接口测试——HttpClient工具的https请求、代理设置、请求头设置、获取状态码和响应头

    目录 https请求 代理设置 请求头设置 获取状态码 接收响应头 https请求 https协议(Secure Hypertext Transfer Protocol) : 安全超文本传输协议, H ...

  8. Android-okhttp下载网络图片并设置壁纸

    在AndroidManifest.xml配置网络访问权限: <!-- 访问网络是危险的行为 所以需要权限 --> <uses-permission android:name=&quo ...

  9. HttpClient登陆后获取并携带cookies发起请求

    最近项目中,用到了登陆后获取并携带cookies发起请求的业务场景,现总结写出来备忘一下. 1.定义存取cookies信息的全局变量 public class HttpUtil { /** * 用来存 ...

随机推荐

  1. Luogu2149 [SDOI2009]Elaxia的路线-最短路+拓扑排序

    Solution 另外$ m <=5e5$. 两条最短路的 最长公共路径 一定是若干条连续的边, 并且满足拓扑序. 于是我们分别 正向 和反向走第二条路径,若该条边同时是两条最短路径上的边, 则 ...

  2. ubuntu如何实现双屏显示

    转载自https://blog.csdn.net/tianmaxingkong_/article/details/50570538

  3. DataTable表连接

    public static System.Data.DataTable TableJoin(System.Data.DataTable dt, System.Data.DataTable dtDeta ...

  4. Homebrew -- mac 缺失包补充工具

    https://brew.sh/index_zh-cn.htmlhttps://brew.sh/ 非root权限下运行 # github 源代码 https://github.com/Homebrew ...

  5. win8 本地化

    先看个简单的案例:新时尚Windows8开发(6):资源 & 本地化 http://www.silverlightchina.net/html/windows8/study/2012/0902 ...

  6. python之常用字符串用法

    1.isdigit=indecimal(判断是否是数字) s=" print(s.isdigit()) 输出为:True 2.format(标识符) a =("I have a { ...

  7. PL/SQL Developer 导出csv文件,用excel打开中文显示乱码

      用PL/SQL Developer的导出csv功能把sql语句的查询结果导出到一个csv文件.这个sql查询的结果里面有中文,最后用execel打开的时候发现中文全部是乱码. 方法 1 导出csv ...

  8. JVM 中知识

    1.栈:(stack) 存放的都是方法中的局部变量 方法的运行一定要在栈当中 局部变量:方法参数,方法{}内部的变量 作用域:一旦超出作用域,立刻从栈中消失 2.堆:(heap) 凡是new出来的东西 ...

  9. Our Future

    The world is betting on how to win the football game: But I'm betting on how to win your heart: Mayb ...

  10. 2018.11.09 bzoj4773: 负环(倍增+floyd)

    传送门 跟上一道题差不多. 考虑如果环上点的个数跟最短路长度有单调性那么可以直接上倍增+floyd. 然而并没有什么单调性. 于是我们最开始给每个点初始化一个长度为0的自环,于是就有单调性了. 代码: ...