Andriod studio 学习 之 okhttp

okhttp协议介绍

okhttp是一个第三方类库,用于android中请求网络。
这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。

首先需要导入依赖

implementation ‘com.squareup.okhttp3:okhttp:3.10.0’
implementation ‘com.squareup.okhttp3:logging-interceptor:3.8.0’

效果图

Andriod studio 学习 之 okhttp_第1张图片

okhttp完成get请求和post请求

package com.example.day001;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Main5Activity extends AppCompatActivity {
    private Button get;
    private Button post;
    private String json;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main5);

        get = (Button) findViewById(R.id.get);
        post = (Button) findViewById(R.id.post);

        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                get("https://news-at.zhihu.com/api/4/news/latest");
            }
        });
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                post("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&phone=121324&passwd=123");
            }
        });

    }
    // //网络请求json串下载
    //okhttpclient
    public void get(String url){
        OkHttpClient.Builder builder=new OkHttpClient.Builder();
        builder.readTimeout(30, TimeUnit.SECONDS);//读取超时
        builder.connectTimeout(20,TimeUnit.SECONDS);//连接超时

        OkHttpClient client=builder.build();//获得一个客户端对象
        Request request = new Request.Builder().get().url(url).build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(Main5Activity.this, "失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                json = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(Main5Activity.this, "内容"+json, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
    //上传
    public void post(String url){
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS).build();
        //表单体(放上传的内容)
//        FormBody.Builder formBody = new FormBody.Builder();
//        for (String k:body.keySet()){
//            formBody.add(k,body.get(k));
//        }
//
//        FormBody formBody1 = formBody.build();
        FormBody formBody = new FormBody.Builder().add("phone", "hsy").add("password", "123").build();
        Request request = new Request.Builder().post(formBody).url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(Main5Activity.this, "上传失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(Main5Activity.this, "结果是"+string, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

    }
}

xml文件



    

你可能感兴趣的:(IT,计算机,安卓)