Url网络下载的常用方式

本文探讨了Url网络下载中常用的两种请求方法——Post和Get。详细阐述了它们的区别与应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android

Url网络下载 Post和Get请求

Post


    //post请求
    private void registerUser() {

        String registerUrl = "http://169.254.230.253:8080/register";
        try {
            URL url = new URL(registerUrl);
            HttpURLConnection postConnection = (HttpURLConnection) url.openConnection();
            postConnection.setRequestMethod("POST");//post 请求
            postConnection.setConnectTimeout(1000*5);
            postConnection.setReadTimeout(1000*5);
            postConnection.setDoInput(true);//允许从服务端读取数据
            postConnection.setDoOutput(true);//允许写入
            postConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");//以表单形式传递参数
            String postParms = "name=1702C2019&password=12345&verifyCode=8888";
            OutputStream outputStream = postConnection.getOutputStream();
            outputStream.write(postParms.getBytes());//把参数发送过去.
            outputStream.flush();
            final StringBuffer buffer = new StringBuffer();
            int code = postConnection.getResponseCode();
            if (code == 200) {//成功
                InputStream inputStream = postConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line = null;//一行一行的读取
                while ((line = bufferedReader.readLine()) != null) {
                    buffer.append(line);//把一行数据拼接到buffer里
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //把从服务端获取的数据提示出来
                        Toast.makeText(MainActivity.this, buffer.toString(), Toast.LENGTH_SHORT).show();
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Get


  private void downloadFile() {
        String downloadurl = "http://www.chinadaily.com.cn/hqzx/images/attachement/jpg/site385/20120924/00221918200911ca40e52b.jpg";
        BufferedInputStream bfs = null;
        FileOutputStream outputStream = null;

        String savepath = "/sdcard/flowergirl.jpg";
        File file = new File(savepath);
        //如果文件存在就先删掉这个文件
        if (file.exists()) {
            file.delete();
        }

        try {
            URL url = new URL(downloadurl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(1000 * 5);
            connection.setReadTimeout(1000 * 5);
            connection.setDoInput(true);
            connection.connect();

            //代表请求成功
            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);

                    }
                });
                bfs = new BufferedInputStream(inputStream);
                outputStream = new FileOutputStream(savepath);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = bfs.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);//写入文件
                }
                outputStream.flush();//强制把数据写入磁盘

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (bfs != null) {
                    bfs.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }

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

        }

    }
package com.example.day14;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PipedOutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private HandlerThread handlerThread;
    private Handler handler;
    private final static int DOWNLOAD = 1;
    private final static int POSTDOWNLOAD = 2;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handlerThread = new HandlerThread("Http");
        handlerThread.start();
        handler = new Httphandler(handlerThread.getLooper());
        //让handler消息运行在子线程
        imageView = findViewById(R.id.imagedown);
        findViewById(R.id.btn1).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
                handler.sendEmptyMessage(DOWNLOAD);
                break;
            case R.id.btn2:
                handler.sendEmptyMessage(POSTDOWNLOAD);

                break;

            default:
                break;

        }
    }


    private class Httphandler extends Handler {

        public Httphandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DOWNLOAD:
                    downloadFile();
                    break;

                case POSTDOWNLOAD:
                    PostdownloadFile();
                default:
                    break;

            }
        }
    }

}

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

   <Button
       android:text="下载文件"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/btn1"
       />

    <Button
        android:text="POST下载文件"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn2"
        />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imagedown"/>


</LinearLayout>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值