1.实例化一个URL对象
2.获取HttpURLConnection对象(初学者建议)
3.设置请求连接属性
4.设置响应码,判断连接结果码
5.读取数据流并解析
GET获取数据
POST提交数据
请求时要开新线程,并在manifssts的根目录下加一句获取权限
<uses-permission-sdk-23 android:name="android.permission.INTERNET"/>
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url=new URL("https://www.baidu.com/?tn=02003390_72_hao_pg");
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
//超时时间
connection.setConnectTimeout(30000);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("Charset","UTF-8");
connection.setRequestProperty("Accept-Charset","UTF-8");
connection.connect();//发起连接
int responseCode=connection.getResponseCode();
String responseMessage=connection.getResponseMessage();
if (responseCode==HttpURLConnection.HTTP_OK){
InputStream inputStream=connection.getInputStream();
String result=streamToString(inputStream);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
POST
安卓9的新特性对Http有限制
解决办法:创建安全配置文件
1.在res文件夹下创建xml/network-security-confing文件
2.增加cleartextTrafficPermitted属性
package com.example.asynctaskproject;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button button;
private TextView textView;
private ProgressBar mProgressBar;
private int INIT_PROGRESS =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化视图
initView();
//设置监听
setListener();
//初始化UI数据
setData();
}
private void setData() {
mProgressBar.setProgress(INIT_PROGRESS );
button.setText("点击下载");
textView.setText("准备下载");
}
private void setListener() {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//下载的事情
}
});
}
/**
初始化视图
*/
private void initView() {
button = findViewById(R.id.button2);
textView = findViewById(R.id.textView2);
}
public class DownloadAsyncTask extends AsyncTask<String ,Integer,Boolean>{
private boolean result;
private String mFilePath;
/**
* 在异步任务前,主线程中
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
//可操作UI
}
/**
* 在另外一个线程处理事件
* String... strings就是入参
* return 结果
* */
@Override
protected Boolean doInBackground(String... strings) {
for (int i = 0; i < 100; i++) {
Log.i(TAG,"DownloadAsyncTask"+strings[0]+strings[1]);
//抛出进度
publishProgress(i);
try {
URL url=new URL("lianjie");
//构造连接,并打开
URLConnection urlConnection=url.openConnection();
InputStream inputStream=urlConnection.getInputStream();
//获得文件总长度用于更新进度条
int contentLength=urlConnection.getContentLength();
//下载地址准备
mFilePath = Environment.getExternalStorageDirectory()+ File.separator+"imooc.apk";
//对下载地址处理
File apkFile=new File(mFilePath);
if (apkFile.exists()){
result = apkFile.delete();
if (!result){
return false;
}
}
//已下载的大小
int downSize=0;
int length;
byte []bytes=new byte[1024];
//创建输出流
OutputStream outputStream=new FileOutputStream(mFilePath);
while ((length=inputStream.read(bytes))!=-1){
//数据放到文件管道里
outputStream.write(bytes,0,length);
downSize+=length;
//发送进度
publishProgress(downSize*100/contentLength);
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
//
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
//主线程中 执行结果 处理
textView.setText("下载完成");
textView.setText(result?"下载完成":mFilePath+"下载失败");
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//收到进度然后处理也是在UI线程
if (values!=null&&values.length>0)
mProgressBar.setProgress(values[0]);
}
@Override
protected void onCancelled() {
super.onCancelled();
//取消
}
@Override
protected void onCancelled(Boolean aBoolean) {
super.onCancelled(aBoolean);//结果参数
//取消
}
}
}