day13_Common Network Request Patterns in Android

Common Network Request Patterns in Android

HttpUrlConnection
1.get request
2.post request
3. Download Web Video/Music/Pictures to SD Card

I. Concept:
1.http: Hypertext Transfer Protocol (client and server), Application Layer Protocol
2.html: Hypertext Markup Language
3.xml: Extensible Markup Language
II. Seven Layers of Network
Application Layer: http
Presentation Layer: Converting People's Understanding into Calculators
Session Layer: Initiate Session
Transport Layer: tcp + udp
Network layer: ip protocol
Data Link Layer:
Physical Layer: Wire
3. http protocol: request protocol + response protocol
1. Request protocol: The client sends to the server
(1) First line of request: mode of request + address + version number
(2) Request header information: some information that the client tells the server about itself
(3) Airline
(4) Request body: data sent by client to server (get request has no request body, post request has request)
2. Response protocol: the server responds to the client
(1) Response first line: version number + response code + response information
(2) Response header information: Content-Length: 4772, which the server tells the client
(3) Airline
(4) Response body: content returned by the server to the client (picture JSON xml)
4.2 software:
fiddler: Used for capturing packages, which can obtain the content of http request protocol and response protocol
Posman: Used for testing interfaces, testing interfaces directly on this software at a time
5. Skills: Use httpurlConnection to make get and post requests
1. The difference between get and post:
get exposes the data sent to the url, and unsafe + primary applications ask the server for data
post places the sent data in the request body, and the secure + main application submits the data to the server
2.get: download file + request picture + request json
3.post: login + registration + upload files
Six. Eight requests, commonly used get and post
1,OPTIONS
Return the HTTP request method supported by the server for specific resources, or test the functionality of the server by sending'*'requests to the web server
2,HEAD
Ask the server for a response that is consistent with the GET request, except that the body of the response will not be returned. This method can obtain the meta-information contained in the response header without transmitting the whole response content.
3,GET
Make requests to specific resources. It essentially sends a request to get a resource on the server. Resources are returned to the client through a set of HTTP headers and rendering data, such as HTML text, or pictures or videos.
4,POST
Submit data to a specified resource for processing requests (such as submitting forms or uploading files). The data is contained in the body of the request.
5,PUT
Upload its latest content to the specified resource location
6,DELETE
Request server deletes resources identified by Request-URL
7,TRACE
Requests received by echo servers, mainly for testing or diagnostics
8,CONNECT
The HTTP/1.1 protocol is reserved for proxy servers that can change the connection to pipeline mode.
7. Common Response Codes: 1xx Message 2xx Successful 3xx Redirection 4xx Client Error 5xx Server

Rolling lyrics effect

//Main Category
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback{
    File file = new File("/sdcard/Misc/Ten miles of spring breeze");
    File file1=new File("/sdcard/Misc/Forward rush - Ten miles of spring breeze.mp3");
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    SeekBar seekBar;
    MediaPlayer mediaPlayer;
    Timer timer;
    int positon=0;
    TextView textView1,textView2;
    ArrayList<Music> list=new ArrayList<>();
    @SuppressLint("HandlerLeak")
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==101){
                if (mediaPlayer!=null){
                    int duration = mediaPlayer.getDuration();
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    Date date=new Date(duration);
                    SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
                    String format = sdf.format(date);
                    seekBar.setMax(duration);
                    seekBar.setProgress(currentPosition);
                    textView2.setText(format);
                    Date date1=new Date(currentPosition);
                    String format1 = sdf.format(date1);
                    textView1.setText(format1);

                    if (list.size()>0){
                        if (positon<list.size()-1){
                            if (currentPosition>=list.get(positon+1).getTime()){
                                positon++;
                            }
                        }
                    }

                    if (positon-1>0){
                        if (currentPosition<=list.get(positon).getTime()){
                            positon--;
                        }
                    }

                }
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        surfaceView=findViewById(R.id.surf);
        seekBar=findViewById(R.id.seekbar);
        textView1=findViewById(R.id.tv1);
        textView2=findViewById(R.id.tv2);

        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(101);
            }
        },0,1);

       mediaPlayer= new MediaPlayer();
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(file1.getPath());
            mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) { }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                mediaPlayer.seekTo(progress);
            }
        });

        StringBuffer stringBuffer=new StringBuffer();
        try {
            FileInputStream fileInputStream=new FileInputStream(file);
            byte[] bytes=new byte[1024];
            int len=0;
            while ((len=fileInputStream.read(bytes))!=-1){
                stringBuffer.append(new String(bytes,0,len));
            }
            Gson gson=new Gson();
            Bean bean = gson.fromJson(stringBuffer.toString(), Bean.class);
            Bean.LrcBean lrc = bean.getLrc();
            String lyric = lrc.getLyric();
            String[] split = lyric.split("\n");
            for (int i = 0; i < split.length; i++) {
//                Log.e("###",split[i]+"");
                String trim = split[i].trim();
                String[] split1 = trim.split("]");
                if(split1.length>=2){
                    String s = split1[0];
                    String substring1 = s.substring(1, 3);
                    String substring2 = s.substring(4, 6);
                    String substring3 = s.substring(7, 9);
//                    Log.e("###",substring1+":"+substring2+":"+substring3);
                    int start=Integer.parseInt(substring1)*60*1000+Integer.parseInt(substring2)*1000+Integer.parseInt(substring3);
                    String text = split1[1];
                    list.add(new Music(text, start));
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < list.size(); i++) {
            Log.e("###",list.get(i).toString());
        }

        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        new MyThread().start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }
    int y=250;
    int x=150;
    class MyThread extends Thread{
        @Override
        public void run() {
            super.run();

            while(true){
                Paint paint=new Paint();
                paint.setColor(Color.BLACK);
                paint.setStrokeWidth(10);
                paint.setTextSize(30);
                Paint paint1=new Paint();
                paint1.setColor(Color.RED);
                paint1.setStrokeWidth(10);
                paint1.setTextSize(50);
                Canvas canvas = surfaceHolder.lockCanvas();
                if(canvas==null){
                    break;
                }
                canvas.drawColor(Color.WHITE);
                if (list.size()>0){
                    for (int i=positon-1;i>=0;i--){
                        canvas.drawText(list.get(i).getText(),x,y-50*(positon-i),paint);
                    }

                    canvas.drawText(list.get(positon).getText(),x,y,paint1);

                    for (int i=positon+1;i<list.size();i++){
                        canvas.drawText(list.get(i).getText(),x,y+50*(i-positon),paint);
                    }
                }

                surfaceHolder.unlockCanvasAndPost(canvas);
            }


        }
    }
}

//Music
public class Music {
    private String text;
    private int time;

    public Music(String text, int time) {
        this.text = text;
        this.time = time;
    }

    @Override
    public String toString() {
        return "Music{" +
                "text='" + text + '\'' +
                ", time=" + time +
                '}';
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }
}
//Analytical Bean Classes
public class Bean {
    private boolean sgc;
    private boolean sfy;
    private boolean qfy;
    private LyricUserBean lyricUser;
    private LrcBean lrc;
    private KlyricBean klyric;
    private TlyricBean tlyric;
    private int code;

    public boolean isSgc() {
        return sgc;
    }

    public void setSgc(boolean sgc) {
        this.sgc = sgc;
    }

    public boolean isSfy() {
        return sfy;
    }

    public void setSfy(boolean sfy) {
        this.sfy = sfy;
    }

    public boolean isQfy() {
        return qfy;
    }

    public void setQfy(boolean qfy) {
        this.qfy = qfy;
    }

    public LyricUserBean getLyricUser() {
        return lyricUser;
    }

    public void setLyricUser(LyricUserBean lyricUser) {
        this.lyricUser = lyricUser;
    }

    public LrcBean getLrc() {
        return lrc;
    }

    public void setLrc(LrcBean lrc) {
        this.lrc = lrc;
    }

    public KlyricBean getKlyric() {
        return klyric;
    }

    public void setKlyric(KlyricBean klyric) {
        this.klyric = klyric;
    }

    public TlyricBean getTlyric() {
        return tlyric;
    }

    public void setTlyric(TlyricBean tlyric) {
        this.tlyric = tlyric;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public static class LyricUserBean {

        private int id;
        private int status;
        private int demand;
        private int userid;
        private String nickname;
        private long uptime;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public int getDemand() {
            return demand;
        }

        public void setDemand(int demand) {
            this.demand = demand;
        }

        public int getUserid() {
            return userid;
        }

        public void setUserid(int userid) {
            this.userid = userid;
        }

        public String getNickname() {
            return nickname;
        }

        public void setNickname(String nickname) {
            this.nickname = nickname;
        }

        public long getUptime() {
            return uptime;
        }

        public void setUptime(long uptime) {
            this.uptime = uptime;
        }
    }

    public static class LrcBean {
      
        private int version;
        private String lyric;

        public int getVersion() {
            return version;
        }

        public void setVersion(int version) {
            this.version = version;
        }

        public String getLyric() {
            return lyric;
        }

        public void setLyric(String lyric) {
            this.lyric = lyric;
        }
    }

    public static class KlyricBean {
        /**
         * version : 0
         * lyric : null
         */

        private int version;
        private Object lyric;

        public int getVersion() {
            return version;
        }

        public void setVersion(int version) {
            this.version = version;
        }

        public Object getLyric() {
            return lyric;
        }

        public void setLyric(Object lyric) {
            this.lyric = lyric;
        }
    }

    public static class TlyricBean {
        /**
         * version : 0
         * lyric : null
         */

        private int version;
        private Object lyric;

        public int getVersion() {
            return version;
        }

        public void setVersion(int version) {
            this.version = version;
        }

        public Object getLyric() {
            return lyric;
        }

        public void setLyric(Object lyric) {
            this.lyric = lyric;
        }
    }
}

Interruption effect

//Main Category
public class MainActivity extends AppCompatActivity {
    VideoView videoView;
    SeekBar seekBar;
    Button button;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==102){
                videoView.setVideoPath("/sdcard/Misc/a.mp4");
                videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        videoView.start();
                    }
                });
            }else if (msg.what==103){
                videoView.setVideoPath("/sdcard/Misc/a.mp4");
                videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        videoView.start();
                    }
                });
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videoView=findViewById(R.id.vv);
        seekBar=findViewById(R.id.seek);
        button=findViewById(R.id.sta);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyGetThread("http://uvideo.spriteapp.cn/video/2019/0719/cc6b8cea-a97a-11e9-a3f8-90b11c479401_wpd.mp4",MainActivity.this,seekBar).start();
            }
        });


    }
}

//thread
public class MyGetThread extends Thread{
    private String url_str;
    private MainActivity activity;
    private SeekBar seekBar;
    int start;
    int end;
    int count=0;
    File file =new File("/sdcard/Misc/a.mp4");
    public MyGetThread(String url_str, MainActivity activity,SeekBar seekBar) {
        this.url_str = url_str;
        this.activity = activity;
        this.seekBar = seekBar;
    }

    @Override
    public void run() {
        super.run();
        try {
            URL url=new URL(url_str);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            if (urlConnection.getResponseCode()==200){
                int contentLength = urlConnection.getContentLength();
                end=contentLength;
                seekBar.setMax(contentLength);
            }

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


        try {
            URL url2=new URL(url_str);
            HttpURLConnection urlConnection2 = (HttpURLConnection) url2.openConnection();
            if (file.exists()){
                start= (int) file.length();
                count+=start;
                if (start==end){
                    activity.handler.sendEmptyMessage(102);
                }
            }
            urlConnection2.setRequestProperty("Range","bytes="+start+"-"+end);
            if (urlConnection2.getResponseCode()==206){
                InputStream inputStream = urlConnection2.getInputStream();
                RandomAccessFile randomAccessFile=new RandomAccessFile(file,"rw");
                randomAccessFile.seek(start);
                byte[] bytes=new byte[1024];
                int len=0;
                while((len=inputStream.read(bytes))!=-1){
                    count+=len;
                    randomAccessFile.write(bytes,0,len);
                    seekBar.setProgress(count);
                    if (count==end){
                        activity.handler.sendEmptyMessage(103);
                    }
                }
            }

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

Keywords: MediaPlayer SurfaceView network xml

Added by metalblend on Fri, 19 Jul 2019 16:19:12 +0300