专高2day1

该代码示例展示了如何在Android应用中处理权限请求,包括读写外部存储权限。此外,它包含了使用IntentService进行GET请求,通过AsyncTask执行POST请求、下载文件以及上传文件的操作。
摘要由CSDN通过智能技术生成
package com.bw.zhuangao2_1;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(Build.VERSION.SDK_INT>Build.VERSION_CODES.M){
            requestPermissions(new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
            },101);
        }
    }
    public void getqingqiu(View view) {//跳转服务get请求
        Intent intent=new Intent(this,MyIntentService.class);
        startService(intent);
    }

    public void posqingxiu(View view) {//pos请求
        new MyThread("http://43.143.146.165:7777/foods/postFoods?").start();
    }
    public void xiazai(View view) {//SDK下载
        new MyAsymcTask().execute("https://img2.baidu.com/it/u=991143399,2017302355&fm=253&fmt=auto&app=138&f=JPEG?w=600&h=499");
    }

    public void shangchaun(View view) {
        new MyUpoadAsync().execute("http://10.161.11.79/add/","/sdcard/guo.jpg");
    }
}
package com.bw.zhuangao2_1;

import android.os.AsyncTask;
public class MyAsymcTask extends AsyncTask<String,Void,String> {//SDK卡封装下载
    @Override
    protected String doInBackground(String... strings) {
        String path = strings[0];
        return HttpUtil.getHttpUtil().down(path);
    }
}


 

package com.bw.zhuangao2_1;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.util.Log;

import androidx.annotation.Nullable;

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 MyIntentService extends IntentService {//服务
    public MyIntentService() {
        super("MyIntentService");
    }
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.i("-----swa", "onHandleIntent: "+"忘记");
        try {
            URL url=new URL("http://43.143.146.165:7777/foods/getFoods?currentPage=1&pageSize=12");
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setReadTimeout(10*1000);//链接时长
            httpURLConnection.setConnectTimeout(10*1000);//读取时长
            httpURLConnection.connect();
            if(httpURLConnection.getResponseCode()==200){
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String str="";
                StringBuilder stringBuilder=new StringBuilder();
                while ((str=bufferedReader.readLine())!=null){
                    stringBuilder.append(str);
                }
                String json=stringBuilder.toString();
                Log.i("-----swa", "onHandleIntent: "+json);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
package com.bw.zhuangao2_1;

import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MyThread extends Thread {
    String path;

    public MyThread(String path) {//懒加载
        this.path = path;
    }

    @Override
    public void run() {
        super.run();
        HttpUtil.getHttpUtil().Pos(path);
    }
}

package com.bw.zhuangao2_1;

import android.os.AsyncTask;

public class MyUpoadAsync extends AsyncTask<String,Void,String> {
    @Override
    protected String doInBackground(String... strings) {
        String result=strings[0];
        String filepath=strings[1];
        HttpUtil.getHttpUtil().upload(result,filepath);
        return null ;
    }
}
package com.bw.zhuangao2_1;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
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.ProtocolException;
import java.net.URL;
import java.util.UUID;
import java.util.zip.InflaterInputStream;

public class HttpUtil {//懒加载封装

    private HttpUtil() {

    }

    private static HttpUtil httpUtil = null;

    public static HttpUtil getHttpUtil() {
        if (httpUtil == null) {
            httpUtil = new HttpUtil();
        }
        return httpUtil;
    }

    public String down(String path) {//get下载
        try {
            URL url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setReadTimeout(2000);
            httpURLConnection.setChunkedStreamingMode(2000);
            httpURLConnection.connect();
            if (httpURLConnection.getResponseCode() == 200) {
                InputStream inputStream = httpURLConnection.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    File path00 = Environment.getExternalStorageDirectory();
                    File file = new File(path00, "guo.jpg");
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    while ((len = inputStream.read()) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                    }
                }
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return path;
    }

    public String Pos(String paths) {//pos请求
        try {
            URL url = new URL(paths);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setReadTimeout(10 * 1000);
            httpURLConnection.setConnectTimeout(10 * 1000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.connect();
            String params = "pageSize=10&currentPage=1";//参数
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(params.getBytes());//转换2进制
            outputStream.flush();//提交
            if (httpURLConnection.getResponseCode() == 200) {
                InputStream inputStream = httpURLConnection.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                StringBuilder stringBuilder = new StringBuilder();
                while ((len = inputStream.read(buffer)) != -1) {
                    stringBuilder.append(new String(buffer, 0, len));
                }
                String json = stringBuilder.toString();
                Log.i("----sas", "run: " + json);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return paths;
    }

    public void upload(String urlpath, String filepath) {
        // 设置边界
        String BOUNDARY = UUID.randomUUID().toString();
        //前面边界符合﹔结尾符号
        String PREFIX = "--", LINE_END = "\r\n";
        // http类型
        String CONTENT_TYPE = "multipart/form-data";
        try {
            //连接
            URL url = new URL(urlpath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(10 * 1000);
            connection.setReadTimeout(10 * 1000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //特殊要求
            connection.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            connection.connect();
            //向外界服务器
            File file = new File(filepath);
            if (file != null) {
                OutputStream outputStream = connection.getOutputStream();
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(PREFIX);
                stringBuffer.append(BOUNDARY);
                stringBuffer.append(LINE_END);
                stringBuffer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + LINE_END);
                stringBuffer.append(LINE_END);
                outputStream.write(stringBuffer.toString().getBytes());
                //开始写真实数据
                InputStream inputStream = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                inputStream.close();
                //开始写结束边界
                outputStream.write(LINE_END.getBytes());
                byte[] end = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                outputStream.write(end);
                outputStream.flush();
                if (connection.getResponseCode() == 200) {

                }

            }

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (ProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值