Android http 下载保存文件

 Android 通过Okhttp3 获取网站bin文件

AndroidManifest.xml 设置权限


    
    
    
    

 


        android:usesCleartextTraffic="true" //明文访问
        android:requestLegacyExternalStorage="true" //访问存储

 MainActivity.java 文件代码

package com.example.networktest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    Uri imageUri;
    String TAG="MainActivity";
    TextView responseText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest=findViewById(R.id.send_request);
        responseText=findViewById(R.id.response_text);
        sendRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: send request");
                sendRequestWithOkHttp();

            }
        });
    }
    

    private void sendRequestWithOkHttp()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://120.77.81.114/bbb.bin").build();
                    Response response = client.newCall(request).execute();

                    String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();

                    if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED)
                    {
                        Log.d(TAG, "request permission");
                        ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                    }
                    else
                    {
                        Log.d(TAG, "has permission");
                    }
                    File file = new File(dir + "/bbb.bin");
                    if(file.exists())
                    {
                        Log.d(TAG, "file exist");
                    }
                    InputStream inputStream;
                    inputStream = response.body().byteStream();

                    Log.d(TAG, "write start2 ");
                    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
                    randomAccessFile.seek(0);
                    byte[] buf = new byte[1024];
                    int len = 0;
                    Log.d(TAG, "write start ");
                    while ((len = inputStream.read(buf)) != -1)
                    {
                        Log.d(TAG, "write len "+len);
                        randomAccessFile.write(buf,0,len);
                    }
                    response.body().close();
                    randomAccessFile.close();
                    showResult("Download Success");
                    
            }
        }).start();
    }
    private void showResponse(final String response)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }

    private void showResult(final String result)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

你可能感兴趣的:(Android,java,android,android,studio)