##Http请求:
Http请求是客户端和服务器端之间,发送请求和返回应答的标准(TCP),客户端发送一个Http请求后,就与服务器建立起了TCP连接,服务端接收到请求并进行处理后返回给客户端相应数据。
##HttpUrlConnection:
HttpUrlConnetion是Java的标准指定网站发送GET请求、POST请求类,继承UrlConnection,可用于向指定网站发送GET请求,POST请求,在使用上相对简单,并且易于扩展。
##如何使用HttpUrlConnection(类比新建一条山泉到家里):
####1、创建URL对象(找水源)
URL url = new URL("https://www.csdn.net/");
####2、通过URL对象调用openconnection()获取HttpURLConnection对象(建大坝打开水闸)
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
####3、HttpURLConnextion对象调用getinputStream()向服务器发送http请求,并获取服务器返回的输入流(建管道输送水)
InputStream inputStream = httpURLConnection.getInputStream();
####4、创建InputStreamReader,存贮输入流(建水池,存水)
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
####5、创建BufferedReader,读取数据(用水桶使用水)
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
##使用 HttpURLConnection获取http请求(以访问csdn网站为列)
####1、修改布局文件,绑定按钮id
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.myapplication.HttpActivity">
<Button
android:id="@+id/http_btn"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="button 1"/>
</LinearLayout>
####2、将按钮设置监听,使用创建线程调用自定义方法,在里面进行http请求,打印获取的网页值
public class HttpActivity extends AppCompatActivity {
private static final String TAG = "HttpActivity";
private Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http);
button1 = findViewById(R.id.http_btn);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
myHttpConnection();
}
}).start();
}
});
}
private void myHttpConnection() {
try {
URL url = new URL("https://csdn.net/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//创建StringBuffer,用来接收输入流的读取内容
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
//通过while语句不断的读取数据放入stringbuffer
while((temp=bufferedReader.readLine())!=null){
stringBuffer.append(temp);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
Log.e(TAG, stringBuffer+"++++++++++++++++++++++++++++++++++" );
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
####3、添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
####4、打印内容
##使用HttpURLConnection实现加载图片实例
####1、创建一个按钮和一个imageview,绑定id
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.myapplication2.DownImageActivity">
<Button
android:id="@+id/download_downlaod_btn"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="down_btn" />
<ImageView
android:id="@+id/downlaod_show_imagv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
####2、创建DownImageActivity,对按钮进行监听,触动按钮时调用AsyncTask执行耗时操作—加载图片
public class DownImageActivity extends AppCompatActivity {
private Button downloadBtn;
private ImageView showImagv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_down_image);
bangID();
downloadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//创建类完成加载在线图片的功能,传入showImagv用于赋值图片
ImageDownload imageDownload = new ImageDownload(showImagv);
//将需要加载的图片地址通过execute()方法发送给doinbackgrond()方法
imageDownload.execute("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=574643212,490700156&fm=27&gp=0.jpg");
}
});
}
private void bangID() {
downloadBtn = findViewById(R.id.download_downlaod_btn);
showImagv = findViewById(R.id.downlaod_show_imagv);
}
}
####在ImageDownload中实现在线图片的加载
public class ImageDownload extends AsyncTask<String,Integer,Bitmap>{
private ImageView showImagv;
//创建构造方法接收传入的imageview
ImageDownload(ImageView imageView){
this.showImagv = imageView;
}
@Override
protected Bitmap doInBackground(String... strings) {
Bitmap showBitmap= null;
try {
//创建URL对象,获取网址
URL url = new URL(strings[0]);
//打开连接
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//接收输入流
InputStream inputStream = httpURLConnection.getInputStream();
//将输入流转换为bitmap赋值
showBitmap = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return showBitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
//设置imageview
showImagv.setImageBitmap(bitmap);
}
}
####成果展现
##使用HttpURLConnection实现下载图片实例
####1、修改布局文件,添加progressbar,按钮和imageview
修改布局文件,添加progressbar,按钮和imageview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="com.example.myapplication2.DownloadShowActivity">
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:id="@+id/downloadshow_pb"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/downloadshow_btn"
android:text="下载图片"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/downloadshow_imagev"/>
</LinearLayout>
####2、创建自定义类继承AsyncTask,完成对图片的下载,同时更新进度条
public class ImageDownload extends AsyncTask<String, Integer, Integer> {
private Context context;
private Button downloadBtn;
private ImageView imageView;
//这两个变量是定义文件将要下载的文件路劲的
private String rootPath;
private String fileName;
private ProgressBar progressBar;
private Bitmap bitmap;
//通过构造方法将activity中需要的控件,context传过来
public ImageDownload(Context context, Button downloadBtn, ImageView imageView, String fileName,ProgressBar progressBar) {
this.context = context;
this.downloadBtn = downloadBtn;
this.imageView = imageView;
//获取文件夹的路径
rootPath = Environment.getExternalStorageDirectory() + "/picture_dir/";
//接收传过来的文件名
this.fileName = fileName;
this.progressBar = progressBar;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
downloadBtn.setEnabled(false);
downloadBtn.setText("正在下载图片");
}
@Override
protected Integer doInBackground(String... strings) {
//首先判断该路径下是否存在文件
if (isExistFile(rootPath + fileName)) {
return 0;
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//当httpURLConnection.getResponseCode() == 200则说明联网成功
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
publishProgress(1, httpURLConnection.getContentLength());
} else {
publishProgress(0);
}
//创建文件的根目录
CreateDir(rootPath);
File file = null;
//创建文件
file = CreateFile(rootPath + fileName);
outputStream = new FileOutputStream(file);
//使用byte【】数组来接收输入流
byte buffer[] = new byte[4 * 1024];
int length = 0;
int sum = 0;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
sum += length;
//实时发送进度条
publishProgress(2, sum);
}
outputStream.close();
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
//判断文件的状态
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
switch (integer) {
case 0:
//第二次按按钮时
downloadBtn.setText("下载完成");
downloadBtn.setEnabled(true);
bitmap = BitmapFactory.decodeFile(rootPath + fileName);
imageView.setImageBitmap(bitmap);
Toast.makeText(context, "存在此文件", Toast.LENGTH_SHORT).show();
break;
case 1:
//第一次下载时
downloadBtn.setText("下载完成");
downloadBtn.setEnabled(true);
//通过文件的路径解析转换成为bitmap图片
bitmap = BitmapFactory.decodeFile(rootPath + fileName);
imageView.setImageBitmap(bitmap);
break;
default:
}
}
//更新进度条
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
switch (values[0]) {
case 0:
Toast.makeText(context,"网络连接异常",Toast.LENGTH_SHORT).show();
break;
case 1:
progressBar.setMax(values[1]);
break;
case 2:
progressBar.setProgress(values[1]);
break;
default:
}
}
private boolean isExistFile(String s) {
File file = new File(s);
if (file.exists()) {
return true;
}
return false;
}
private boolean CreateDir(String rootPath) {
File file = new File(rootPath);
boolean isCreateDir = file.mkdir();
return isCreateDir;
}
private File CreateFile(String s) {
File file = new File(s);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
}
####3、在activity调用自定义类,启动子线程,同时添加动态获取权限代码
#####Android6.0权限分配可阅读这篇博客
Android6.0权限分配链接
public class DownloadShowActivity extends AppCompatActivity {
private ProgressBar progressBar ;
private Button downloadBtn;
private ImageView imageView;
private String TAG = "DownloadShow2Activity";
private PermissionHelper permissionHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_show);
bangID();
downloadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
permissionHelper = new PermissionHelper(DownloadShowActivity.this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
permissionHelper.request(new PermissionHelper.PermissionCallback() {
@Override
public void onPermissionGranted() {
//通过调用构造方法传值
ImageDownload imageDownload = new ImageDownload(DownloadShowActivity.this,downloadBtn,imageView,"aaapic.jpg",progressBar);
//启动线程
imageDownload.execute("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=574643212,490700156&fm=27&gp=0.jpg");
Log.d(TAG, "onPermissionGranted() called");
}
@Override
public void onIndividualPermissionGranted(String[] grantedPermission) {
Log.d(TAG, "onIndividualPermissionGranted() called with: grantedPermission = [" + TextUtils.join(",",grantedPermission) + "]");
}
@Override
public void onPermissionDenied() {
Log.d(TAG, "onPermissionDenied() called");
}
@Override
public void onPermissionDeniedBySystem() {
Log.d(TAG, "onPermissionDeniedBySystem() called");
}
});
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (permissionHelper != null) {
permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void bangID() {
progressBar = findViewById(R.id.downloadshow_pb);
downloadBtn = findViewById(R.id.downloadshow_btn);
imageView = findViewById(R.id.downloadshow_imagev);
}
}
####4、效果展现