Android uses HTTP protocol to access the network

Keywords: Android Java OkHttp

At present, there are two commonly used methods to send HTTP requests, one is HttpURLConnection (official recommended usage), the other is OkHttp (developed by Square)

The first method:

Get HttpURLConnection instance

URL url = new URL("https://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();

Set the method used for HTTP requests

There are two common methods for HTTP requests: get and post. There are other settings available, such as connection timeout and read timeout in seconds

 connection.setRequestMethod("GET");
 connection.setConnectTimeout(80000);
 connection.setReadTimeout(80000);

Call getInputStream method to get the returned input stream

InputStream in  = connection.getInputStream();

Read input stream

reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine())!= null){
        response.append(line);
     }

Full code:

package com.example.vm510l.networktest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView reponseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button)findViewById(R.id.send_request);
        reponseText = (TextView)findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.send_request){
            sendRequestWithHttpURLConnection();
        }
    }

    private void sendRequestWithHttpURLConnection(){
        new Thread(new Runnable(){
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try{
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(80000);
                    connection.setReadTimeout(80000);
                    InputStream in  = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine())!= null){
                        response.append(line);
                        Log.d("1","66666");
                    }
                    showReponse(response.toString());
                } catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(reader != null){
                        try{
                            reader.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                    if(connection != null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showReponse(final String response){
        runOnUiThread(new Runnable(){
            @Override
            public void run() {
                reponseText.setText(response);
            }
        });
    }



}

The second method:

Create an OkHttpClient instance

OkHttpClient client = new OkHttpClient();

Create a Request object

Request request = new Request.Builder()
                            .url("http://www.baidu.com")
                            .build();

Call the newCall method of OkHttpClient to create a call object (used to send a request and get the return data of the server)

Response response = client.newCall(request).execute();

Analytical data

String responseData = response.body().string();
showReponse(responseData);

Complete code

Where sendRequestWithHttpURLConnection was called before

private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://www.baidu.com")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showReponse(responseData);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

 

Posted by tlavelle on Mon, 30 Dec 2019 23:31:54 -0800