access network

Using HttpURLConnection

1. Apply for permission

   

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

 

2. The button registers the onclick() event and executes the method

sendRequestWithHttpURLConnection();

 

3. Display the acquired data in the textView

private void sendRequestWithHttpURLConnection() {
     // Open a thread to initiate a network request
 new Thread( new Runnable() {
         @Override
 public void run() {
            HttpURLConnection connection = null;
            BufferedReader reader = null;
            try {
                URL url = new URL( https://www.baidu.com ); //Note that it is https, writing http cannot get data
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);
                InputStream in = connection.getInputStream();
                // Read the obtained input stream below
 reader = new BufferedReader( new InputStreamReader(in));
                 final StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                    Log.w("myyyyyyyyyyyyy",response.toString());
                }
                runOnUiThread(new Runnable() {
                    @Override
public void run() {
                        textView.setText(response);
                    }
                });

            } catch (Exception e) {
                e.printStackTrace ();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace ();
                    }
                }
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    }).start();
}

 

Use OKHttp3

Link address; http://blog.csdn.net/itachi85/article/details/51190687

 

The breakpoint download function of OKHttp3:

Request request = new Request.Builder()
         // Breakpoint download, specify which byte to start downloading from.
 addHeader( "RANGE" , "bytes=" + downloadedLength + "-" )
        .url(downloadUrl)
        .build();
savedFile.seek(downloadedLength); // skip downloaded bytes

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326230194&siteId=291194637