Android初级开发(九)——网络交互—OkHttp

来源:互联网 发布:php 接口开发加密 编辑:程序博客网 时间:2024/06/08 01:54

一、使用OkHttp的步骤
1、在项目中添加OkHttp库的依赖
在File->Project Structure->app->Dependencies->+(添加)->搜索OkHttp->找“com.squareup.okhttp3:okhttp:3.8.1”确定添加
这里写图片描述

2、首先创建OkHttpClient实例

OkHttpClient client = new OkHttpClient();

3、发送GET请求或POST请求
GET请求:创建一个request对象,并在build()前连缀很多方法来丰富这个request对象

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

POST请求:先构建body对象存放数据,然后在Request.Builder()调用post方法将body对象传入

RequestBody requestBody = new FormBody.Builder()                                    .add("username","admin")                                    .add("password","123456")                                    .build(); Request request = new Request.Builder()                                    .url("http://www.baidu.com")                                    .post(requestBody)                                    .build();

4、调用execute()方法发送请求并获取服务器返回的数据

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

二、实现一下吧
1、效果图
效果图和上一篇HttpURLConnection的使用中的是一样的,因为发送都是访问百度页面的请求
这里写图片描述

2、布局文件

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <Button        android:id="@+id/send_request"        android:layout_width="match_parent"        android:layout_height="80dp"        android:text="发送请求"        android:textSize="25dp"/>    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent">        <TextView            android:id="@+id/response_text"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </ScrollView></LinearLayout>

3、MainActivity.java

public class MainActivity extends AppCompatActivity {    Button sendRequest;    TextView responseText;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        responseText = (TextView) findViewById(R.id.response_text);        sendRequest = (Button) findViewById(send_request);        sendRequest.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                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();                            showResponse(responseData);                        }catch (Exception e){                            e.printStackTrace();                        }                    }                }).start();            }        });    }    private void showResponse(final String response) {        runOnUiThread(new Runnable() {            @Override            public void run() {                //在这里进行UI操作,将结果显示到界面上                responseText.setText(response);            }        });    }}

4、在清单文件中声明网络权限

<uses-permission android:name="android.permission.INTERNET"/>
阅读全文
0 0
原创粉丝点击