HTTPURLConnection
1.什么是Http请求
1.HTTP请求是客户端和服务器端之间,发送请求和返回应答的标准(TCP)。
2.客户端发出一个HTTP请求后,就与服务器建立起了TCP连接,服务端接收到请求并进行处理后返回给客户端响应数据。
2.什么是HTTPURLConnection
URLConnection是个抽象类,它有两个直接子类分别是HttpURLConnection和JarURLConnection。另外一个重要的类是URL,通常URL可以通过传给构造器一个String类型的参数来生成一个指向特定地址的URL实例。
每个HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络。请求后在HttpURLConnection的InputStream或OutputStream上调用close()方法可以释放与此实例关联的网络资源,但对共享的持久连接没有任何影响。如果在调用 disconnect() 时持久连接空闲,则可能关闭基础套接字。
Android上发送HTTP请求的方式
HttpURLConnection: HttpURLConnection是java的标准指定网站发送GET请求、POST请求类,HttpURLConnection继承自URLConnection,可用于向指定网站发送GET请求、POST请求,HttpURLConnection在使用上相对简单,并且易于扩展,推荐使用。
Httpent: Androd SDK提供了Apache的HipCient,它是一个完善的客户端。它提供了对HTTP协议的全面支持,可以使用HttpClient的对象来执HTTP GET和HTTP POST调用。在android 6.0 (API 23)中,Google已经移验了Apache HttpClient相关的类,在此就不在讲述HttpClient的使用。
3.如何使用HTTPURLConnection
1.创建URL对象。
2.通过URL对象调用openCo nn ection()方法获得HttpU RLConnection对象。
3.HttpURLConnection对象设置其他连接属性。
4.HttpURLConnection对象调用getInputStream()方法向服务器发送http请求并获取到服务器返回的输入流。
5.读取输入流,转换成String字符串。
注意:
1.在Android中访问网络必须添加网络权限
2.在Android中访问网络必须放在子线程中执行
4.使用HTTPURLConnection获取Http请求
package com.example.pc.http;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main2Activity extends AppCompatActivity {
private Button getwebBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
bindID();
getwebBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
getWebInfo();
}
}).start();
}
});
}
private void getWebInfo() {
try {
//1.找水源--创建URL
URL url = new URL("http://www.baidu.com/");
//2.开水闸--openconnection
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//3.建管道--InputStream
InputStream inputStream = httpURLConnection.getInputStream();
//4.建蓄水池蓄水--InputStreamReader
InputStreamReader reader = new InputStreamReader(inputStream,"UTF-8");
//5.水桶装水--BufferedReader
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
while ((temp=bufferedReader.readLine())!=null){
stringBuffer.append(temp);
}
bufferedReader.close();
reader.close();
inputStream.close();
Log.e("MAIN",stringBuffer.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void bindID() {
getwebBtn = findViewById(R.id.bt);
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.example.pc.http.Main2Activity">
<Button
android:id="@+id/bt"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="点击"
android:textSize="50sp"/>
</android.support.constraint.ConstraintLayout>
使用HTTPURLConnection加载实例
package com.example.pc.http;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class Main3Activity extends AppCompatActivity {
private Button loadBtn;
private ImageView loadImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
bindID();
loadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImgLoadTask task = new ImgLoadTask(loadImg);
task.execute("http://img31.mtime.cn/mg/2012/10/30/201631.37192876.jpg");
}
});
}
private void bindID() {
loadBtn = findViewById(R.id.loadpic_btn);
loadImg = findViewById(R.id.loadpic_img);
}
}
<?xml version="1.0" encoding="utf-8"?>
<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.pc.http.Main3Activity">
<Button
android:id="@+id/loadpic_btn"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="点击按钮"
android:textSize="50sp"/>
<ImageView
android:id="@+id/loadpic_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitCenter"/>
</LinearLayout>
package com.example.pc.http;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by pc on 2018/3/13.
*/
public class ImgLoadTask extends AsyncTask<String,Integer,Bitmap> {
private ImageView imageView;
public ImgLoadTask(ImageView iv){
this.imageView = iv;
}
@Override
protected Bitmap doInBackground(String... strings) {
//加载网络图片,最后获取到一个Bitmap对象,返回Bitmap对象
Bitmap bm = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);//把输入流转换成Bitmap类型对象
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
}
使用HTTPURLConnection下载实例
注意下载需要获取文件的读写权限
package com.example.pc.http;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by pc on 2018/3/14.
*/
public class Download2Task extends AsyncTask<String,Integer,Integer> {
private String dirPath;//下载图片的目录 例如/root/pic/
private String filePath;//文件存储具体位置 例如/root/pic/a.jpg
private Context context;
private ImageView loadImg;
public Download2Task(Context context,ImageView loadImg){
this.context = context;
this.loadImg = loadImg;
}
@Override
protected Integer doInBackground(String... strings) {
//判断目录是否存在,如果不存在就创建这个目录
dirPath = Environment.getExternalStorageDirectory()+"/download_pics/";
File dir = new File(dirPath);//目录对象
if (!dir.exists()){
dir.mkdir();
}
//判断文件是否存在如果不存在则创建文件
String fileName = strings[1];//要储存的图片名字
filePath = dirPath+strings[1];
File file = new File(filePath);//创建文件对象
if (file.exists()){
return -1;
}else {
try {
file.createNewFile();//不存在就创建这个文件
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode()==200){
//判断返回码是否正常,若正常创建输入流,否则就直接返回
inputStream = connection.getInputStream();
}else {
return -2;
}
outputStream = new FileOutputStream(file);
int length = 0;
byte[] buffer = new byte[4*1024];//缓冲区
while ((length=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.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 1:
//正常下载
Toast.makeText(context,"下载完成",Toast.LENGTH_SHORT).show();
Bitmap bm= BitmapFactory.decodeFile(filePath);
loadImg.setImageBitmap(bm);
break;
case -1:
//文件已存在
Toast.makeText(context,"文件已存在",Toast.LENGTH_SHORT).show();
break;
case -2:
//网络异常
Toast.makeText(context,"网络异常",Toast.LENGTH_SHORT).show();
break;
}
}
}
package com.example.pc.http;
import android.Manifest;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.master.permissionhelper.PermissionHelper;
public class Main4Activity extends AppCompatActivity {
private Button loadBtn;
private ImageView loadImg;
private String picUrl = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=617231263,187954695&fm=27&gp=0.jpg";
private PermissionHelper permissionHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
bindID();
loadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
permissionHelper = new PermissionHelper(Main4Activity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
permissionHelper.request(new PermissionHelper.PermissionCallback() {
@Override
public void onPermissionGranted() {
//获取到权限
Download2Task task =new Download2Task(Main4Activity.this,loadImg);
task.execute(picUrl,"0001.jpg");
}
@Override
public void onIndividualPermissionGranted(String[] grantedPermission) {
}
@Override
public void onPermissionDenied() {
}
@Override
public void onPermissionDeniedBySystem() {
}
});
}
});
}
private void bindID() {
loadBtn = findViewById(R.id.dowenloadBtn);
loadImg = findViewById(R.id.loadpic1_img);
}
@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);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<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.pc.http.Main4Activity">
<Button
android:id="@+id/dowenloadBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下载" />
<ImageView
android:id="@+id/loadpic1_img"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>