2018-07-18Http协议访问网络

Http协议工作原理 :

客户端向服务器端发送一条HTTP请求,服务器收到请求之后会返回一些数据给客户端,然后客户端再对这些返回的数据进行解析和处理

手动发送Http请求(发送部分)

1.使用HttpURLConnection

首先要获取到一个HTTPURLConnection实例,先new出一个URL对象,

URL url = new URL("www.baidu.com") //传入目标网站的网络地址

然后再调用openConnection()方法,结合起来的写法是

HttpURLConnection connection  =   (HttpURLConnection) url.openConnection;

得到HttpURLConnection实例之后,我们可以设置一些关于Http请求的方法,常用的方法选择有两个

1.GET  //希望从服务器获取数据

2. POST   / /希望提交数据给服务器

调用方式为  connection.setRequestMethod("GET")

当然还可以对Http请求做一些自由的定制

例如显示连接超时和读取超时的秒数

connection.setConnectTimeout(5000);

connection.setReadTimeout(5000);

接收读取服务器返回的输入流

调用getInputStream()方法获取服务器返回的输入流

InputStream in = connection.getInputStream();

关闭Http

最后调用disconnection()方法把Http连接关掉

connection.disconnection;

下面简单讲一个发送Http请求并接受服务器返回的数据小例子

2.使用OkHttp

在使用OkHttp之前,先要在build.gradle添加依赖库

compile 'com.squareup.okhttp3:okhttp:3.4.1' //后面的3.4.1是okhttp的版本号

接下来来看OkHttp的具体用法

首先创建一个OkHttpClient 实例

OkHttpClient client = new OkHttpClient();

然后创Request对象

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

之后调用OkHttpClient的newCall()方法创建一个Call对象,并调用execute()方法

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

Response 的对象 response 就是服务器返回的数据

但是我们要得到具体的内容,这样写

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

例子如下

public class MainActivityextends AppCompatActivityimplements View.OnClickListener {

TextViewresponseText;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Button sendRequest = (Button) findViewById(R.id.send_request);

        responseText = (TextView) findViewById(R.id.response_text);

        sendRequest.setOnClickListener(this);

    }

@Override

    public void onClick(View v) {

if (v.getId() == R.id.send_request) {

//在Send Request按钮的点击事件中调用了sendRequestWithHttpURLConnection();方法

            sendRequestWithOkHttp();

        }

}

private void sendRequestWithOkHttp() {

//开启线程来发送网络请求

        new Thread(new Runnable() {

@Override

            public void run() {//先开启一个子线程

                try {

//使用OkHttp

                    OkHttpClient client =new OkHttpClient(); //创建一个OkHttpClient对象

                    Request request =new Request.Builder().url("http://www.baidu.com").build(); //创建一个Request对象并且调用Builder().url()

                    Response response = client.newCall(request).execute();  //使用client对象来调用newCall()方法获取服务器返回的数据

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

                    showResponse(responseData);

                }catch (Exception e) {

e.printStackTrace();

                }

}

}).start();

    }

private void showResponse(final String response) {

//将子线程切换为主线程

//android是不允许在子线程进行UI操作的

        runOnUiThread(new Runnable() {

@Override

            public void run() {

//在这里进行UI操作,将结果显示在页面上

                responseText.setText(response);

            }

});

    }

}

最后就是请求网络权限了

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

猜你喜欢

转载自blog.csdn.net/qq_40111789/article/details/81183355
今日推荐