Android进阶——HttpURLConnection的用法

HttpURLConnection的获取请求

(一)什么是Http请求

概念:

是指从客户端服务器端的发送消息和返回应答的标准(TCP)。

方式:
  1. get方式属于明文传参,直接通过地址访问,但不安全;
  2. post方式属于暗文传参,在页面输入城市后,点击按钮。

(二)什么是HttpURLConnection

概念:

HttpURLConnection是URLConnection的子类,每个HttpURLConnection 实例都可用于生成单个请求。


(三)HttpURLConnection的使用方法

步骤:
  1. 创建URL对象;
  2. 通过URL对象调用openConnection()方法获得HttpURLConnection对象;
  3. HttpURLConnection对象设置其他链接属性;
  4. HttpURLConnection对象调用getInputStream()方法向服务器发送http请求并获取到服务器返回的输入流;
  5. 读取输入流,转换成String字符串。

访问网络添加权限;
访问网放在子线程中执行。

网络访问权限:

<uses-permission android:name="android.permission.INTERNET" />

(四)用HttpURLConnection获取Http请求

代码展示:

public class MainActivity extends AppCompatActivity {
    private Button btn;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bindID();

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getWebInfo();
                    }
                }).start();
            }
        });

    }

    private void getWebInfo() {
        try {
            //1.找水源
            URL url = new URL("https://www.csdn.net/");
            //2.建闸道
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//            httpURLConnection.setConnectTimeout(1000);
            //3.建管道
            InputStream inputStream = httpURLConnection.getInputStream();
            //4.蓄水池
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            //装桶
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            StringBuffer stringBuffer=new StringBuffer();
            String temp=null;
            while ((temp=bufferedReader.readLine())!=null){
                stringBuffer.append(temp);
            }

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();

            Log.e("MAIN",stringBuffer.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void bindID() {
        btn = findViewById(R.id.main_btn);
    }


}

(五)用HttpURLConnection加载图片

ImageLoadTask外部类

public class ImageLoadTask extends AsyncTask<String, Integer, Bitmap> {

    private ImageView imageView;

    //构造方法进行传值
    public ImageLoadTask(ImageView view) {
        this.imageView = view;
    }

    @Override
    protected Bitmap doInBackground(String... strings) {
        Bitmap bitmap = null;
        try {
            URL url = new URL(strings[0]);
            URLConnection imageLoadTask = url.openConnection();
            InputStream inputStream = imageLoadTask.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        imageView.setImageBitmap(bitmap);
    }
}

Activity

public class ImgloadActivity extends AppCompatActivity {

    private Button button;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imgload);
        bindID();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ImageLoadTask task=new ImageLoadTask(imageView);
                task.execute("http://img31.mtime.cn/mg/2012/10/30/201631.37192876.jpg");

            }
        });
    }



    private void bindID() {
        button=findViewById(R.id.main_btn);
        imageView=findViewById(R.id.main_img);
    }
}

(六)下载网络资源

添加权限:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
public class DownLoadText extends AsyncTask<String, Integer, Integer> {

    private String dirpath;
    private String filepath;

    private Context context;
    private ImageView imageView;

    public DownLoadText(Context context, ImageView imageView) {
        this.context = context;
        this.imageView = imageView;

    }


    @Override
    protected Integer doInBackground(String... strings) {

        String filename = strings[1];
        dirpath = Environment.getDataDirectory() + "/download.jpg";
        File dir = new File(strings[1]);
        if (!dir.exists()) {
            dir.mkdir();

        }
        filepath = dirpath + strings[1];
        File file = new File(filepath);
        if (file.exists()) {
            return -1;
        } else {
            try {
                file.createNewFile();
            } catch (IOException e) {

            }
        }
        //输入输入流,输出流
        InputStream inputStream = null;
        OutputStream outputStream = null;


        try {
            //创建URL
            URL url = new URL(strings[0]);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            //判断返回码
            if (httpURLConnection.getResponseCode() == 200) {
                inputStream = httpURLConnection.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.flush();
            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_LONG).show();
                Bitmap bitmap = BitmapFactory.decodeFile(filepath);
                imageView.setImageBitmap(bitmap);
                break;
            case -2:
                //网络异常
                Toast.makeText(context, "网络异常", Toast.LENGTH_LONG).show();
                break;
            case -1:
                //文件已存在
                Toast.makeText(context, "文件已存在", Toast.LENGTH_LONG).show();
                break;
        }
    }
}

public class MainActivity extends AppCompatActivity {
    private Button button;
    private ImageView imageView;
    private String  picurl="http://img02.sogoucdn.com/app/a/100520093/ca86e620b9e623ff-d72d635343d5bade-dcf2acda7a45cb44f172db138bdf8d2d.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bindID();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownLoadText downLoadText=new DownLoadText(MainActivity.this,imageView);
                downLoadText.execute(picurl,"pic2.jpg");
            }
        });
    }

    private void bindID() {
        button=findViewById(R.id.main_btn);
        imageView=findViewById(R.id.main_img);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值