使用OKHttpClient访问网络

使用OKHttpClient前要引入依赖:

在build.gradle(Moduel :app)中添加

implementation 'com.squareup.okhttp3:okhttp:3.14.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.14.1'
implementation 'com.squareup.okio:okio:1.6.0'

1. GET(同步或异步)

        //创建OKHttpClient
        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                .connectTimeout(50, TimeUnit.SECONDS)
                .readTimeout(50,TimeUnit.SECONDS)
                .writeTimeout(50,TimeUnit.SECONDS)
                .build();
        //创建请求
        Request request=new Request.Builder()
                .url( new URL("http://www.baidu.com") )
                .get() //GET方式用
                .build();
        //创建Call
        Call call=okHttpClient.newCall(request);
        
        //同步
        Response response=call.execute();
        ResponseBody responseBody=response.body();//获取ResponseBody
        //异步
        Response response=call.enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                //连接失败调用
            }
            public void onResponse(Call call, Response response) throws IOException {
                //连接成功调用
                ResponseBody responseBody=response.body();//获取ResponseBody
            }
        });

2. POST(同步或异步)

        //创建OKHttpClient
        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                .connectTimeout(50, TimeUnit.SECONDS)
                .readTimeout(50,TimeUnit.SECONDS)
                .writeTimeout(50,TimeUnit.SECONDS)
                .build();
        //创建RequestBody或FormBody或MultipartBody
        RequestBody requestBody = RequestBody.create( 
                MediaType.parse("application/x-www-form-urlencode;charset=utf-8"), 
                "username="+ URLEncoder.encode("myUserName")+"&password="+URLEncoder.encode("123456"));
        FormBody formBody = new FormBody.Builder()
                .add("name","myUserName")
                .add("sex","男")
                .add("age","20")
                .build();
        MultipartBody multipartBody=new MultipartBody.Builder()
                .addFormDataPart("name","myUserName")
                .addFormDataPart("sex","女")
                .addFormDataPart("File",file.toString(),requestBody)
                .build();
        //创建请求
        Request request=new Request.Builder()
                .url( new URL("http://www.baidu.com") )
                .post(requestBody) //POST方式用,参数为RequestBody或FormBody或MultipartBody
                .build();
        //创建Call
        Call call=okHttpClient.newCall(request);

        //同步
        Response response=call.execute();
        ResponseBody responseBody=response.body();//获取ResponseBody
        //异步
        Response response=call.enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                //连接失败调用
            }
            public void onResponse(Call call, Response response) throws IOException {
                //连接成功调用
                ResponseBody responseBody=response.body();//获取ResponseBody
            }
        });

RequestBody.create()中的参数 MediaType的 .pase()方法的参数决定了网络文件的类型及编码方式

MultipartBody可添加多种类型数据

3. Response及ResponseBody的使用

    //获取返回类型
    String contentType = response.header("Content-Type");
    //判断返回值类型
    if(contentType!=null&&contentType.equals("application/octet-stream")){
        //返回类型为 流
        ResponseBody responseBody = response.body();
        InputStream inputStream=responseBody.byteStream();
    }
    else if(contentType!=null&&contentType.equals("application/json")){
        //返回类型为 json
        ResponseBody responseBody = response.body();
        String json=responseBody.toString();
    }

4. 网络文件类型

text/html   HTML格式
text/pain   纯文本格式
image/jpeg  jpg图片格式
application/json   JSON数据格式
application/octet-stream   二进制流数据
application/x-www-form-urlencode   form表单encType属性的默认格式,表单数据以Key/value的形式发送到服务器端
multipart/form-data   表单上传文件的格式 

你可能感兴趣的:(网络,android,java)