• JAVA网络请求--------Okhttp3


    2019-10-30   20:18:19

    只记录使用方法,只记录使用方法,只记录使用方法。

    okhttp3是一个能在java和安卓上使用的网络请求框架

    一丶导入

      .maven导入方式

    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>4.2.2</version>
    </dependency> 

      .gradle引入方式

    compile 'com.squareup.okhttp3:okhttp:4.2.2'

      .jar包导入

        -链接:https://pan.baidu.com/s/1BFMcd0ntRTzjhbrBEcis_g 提取码:74fb

    二丶get请求

    package com.lxl.learn.okhttp3;
    
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    
    public class Learn_Okhttp3 {
    
        public static void main(String[] args) throws Exception {
            OkHttpClient client = new OkHttpClient();
            Request req = new Request.Builder().url("https://www.baidu.com/").build();
            Response rep = client.newCall(req).execute();
            System.out.println("返回码:"+rep.code());
            //rep.header("这里写头,可以得到相关值")
            //rep.body().string() 只能被调用一次,在要对返回内容做多次操作时用字符串存一下
            System.out.println("返回内容:"+rep.body().string());
        }
    
    }

      1.添加请求头参数

    package com.lxl.learn.okhttp3;
    
    import java.io.IOException;
    
    import okhttp3.Call;
    import okhttp3.Callback;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    
    public class Learn_Okhttp3 {
    
        public static void main(String[] args) throws Exception {
            OkHttpClient client = new OkHttpClient();
            Request req = new Request.Builder()
                    .url("https://www.baidu.com/")
                    .addHeader("键", "值")
                    .addHeader("键", "值")
                    //.......
                    .build();
            //异步请求
            client.newCall(req).enqueue(new Callback() {
                
                @Override
                public void onResponse(Call arg0, Response arg1) throws IOException {
                    //请求成功会执行
                    System.out.println("返回码:"+arg1.code());
                    System.out.println(arg1.body().string());
                }
                
                @Override
                public void onFailure(Call arg0, IOException arg1) {
                    //请求失败或网络错误会执行这里
                    System.out.println("请求失败");
                }
            });
        }
    
    }

    三丶POST请求

    package com.lxl.learn.okhttp3;
    
    
    import okhttp3.Call;
    import okhttp3.FormBody;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.RequestBody;
    import okhttp3.Response;
    
    public class Learn_Okhttp3 {
    
        public static void main(String[] args) throws Exception {
            OkHttpClient client = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("键", "值")
                    //例如 .add("user","123456")
                    //     .add("passwd","abc1234")
                    .build();
            Request req = new Request.Builder()
                    .url("https://www.baidu.com/")
                    .addHeader("键", "值")    //header方法是覆盖,addHeader才是添加
                    .addHeader("键", "值")
                    .post(body)
                    .build();
            //同步请求
            Call call = client.newCall(req);
            Response response = call.execute();
            System.out.println("返回码:"+response.code());
            System.out.println(response.body().toString());
        }
    }
    RequestBody 一般用于普通表单提交
    其中提交数据不只是有普通表单,有时是json,有时是数据文件,这时就必须写上
    RequestBody的数据格式,一般常见的三种:
    • application/x-www-form-urlencoded 数据是个普通表单
    • multipart/form-data 数据里有文件
    • application/json 数据是json
    普通表单数据格式可以省略:因为FormBody继承了RequestBody,它已经指定了数据类型为application/x-www-form-urlencoded。
      1.json数据提交
    package com.lxl.learn.okhttp3;
    
    
    import org.json.simple.JSONObject;
    
    import okhttp3.Call;
    import okhttp3.MediaType;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.RequestBody;
    import okhttp3.Response;
    
    public class Learn_Okhttp3 {
    
        public static void main(String[] args) throws Exception {
            OkHttpClient client = new OkHttpClient();
            
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            
            JSONObject json = new JSONObject();
            json.put("user", "123456");
            
            RequestBody body = RequestBody.create(JSON,json.toJSONString());
            
            Request req = new Request.Builder()
                    .url("https://www.baidu.com/")
                    .post(body)
                    .build();
            //同步请求
            Call call = client.newCall(req);
            Response response = call.execute();
            System.out.println("返回码:"+response.code());
            System.out.println(response.body().toString());
        }
    }

       2.数据文件提交

    package com.lxl.learn.okhttp3;
    
    
    import java.io.File;
    
    import okhttp3.Call;
    import okhttp3.MediaType;
    import okhttp3.MultipartBody;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.RequestBody;
    import okhttp3.Response;
    
    public class Learn_Okhttp3 {
    
        public static void main(String[] args) throws Exception {
            OkHttpClient client = new OkHttpClient();
            File file = new File("e:\a.jpg");
            //MultipartBody也是继承了RequestBody
            /*源码可知它适用于这五种Content-Type:
             * 
             * public static final MediaType MIXED = MediaType.parse("multipart/mixed");
             * public static final MediaType ALTERNATIVE = MediaType.parse("multipart/alternative");
             * public static final MediaType DIGEST = MediaType.parse("multipart/digest");
             * public static final MediaType PARALLEL = MediaType.parse("multipart/parallel");
             * public static final MediaType FORM = MediaType.parse("multipart/form-data");
             * 
             */
            RequestBody body = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
                    .build();
            
            Request req = new Request.Builder()
                    .url("https://www.baidu.com/")
                    .post(body)
                    .build();
            //同步请求
            Call call = client.newCall(req);
            Response response = call.execute();
            System.out.println("返回码:"+response.code());
            System.out.println(response.body().toString());
        }
    }

       3.使用异步请求

        在android中一般都是使用异步的处理,OkHttpClient.newCall(Request req).enqueue(Callback call),但是在异步请求后不能直接修改ui控件,android中不允许后台线程修改ui,只允许主线程修改

        4.下载文件

    package com.lxl.learn.okhttp3;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    import okhttp3.Call;
    import okhttp3.Callback;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    
    public class Learn_Okhttp3 {
    
        public static void main(String[] args) throws Exception {
            String url = "http://b.hiphotos.baidu.com/image/pic/item/908fa0ec08fa513db777cf78376d55fbb3fbd9b3.jpg";
            Request request = new Request.Builder().url(url).build();
            new OkHttpClient().newCall(request).enqueue(new Callback() {
                
                @Override
                public void onResponse(Call arg0, Response arg1) throws IOException {
                    System.out.println("大小:"+arg1.body().contentLength()/1024+"kb");
                    InputStream is = arg1.body().byteStream();
    
                    byte[] buf = new byte[2048];
    
                    File file = new File("E:\a.jpg");
                    if(file.exists()) file.createNewFile();
                    FileOutputStream fo = new FileOutputStream(file);
                    
                    int len = 0;
                    while((len = is.read(buf)) != -1) {
                        fo.write(buf,0,len);
                    }
                    fo.flush();
                    if(is != null)
                        is.close();
                    if(fo != null)
                        fo.close();
                    System.out.println("下载完成");
                }
                
                @Override
                public void onFailure(Call arg0, IOException arg1) {
                    
                }
            });
    
        }
    }

      暂时记这点,有时间详细看看源码。

  • 相关阅读:
    iOS Icon尺寸、iPhone Ratina 分辨率
    Xcode常用设置
    Objective-C中的数据类型、常量、变量、运算符与表达式
    格式化输出
    Objective-C程序结构及语法特点
    构造数据类型、枚举类型
    数组、字符串
    冒泡排序
    常量、变量
    函数
  • 原文地址:https://www.cnblogs.com/lxlw/p/11767888.html
Copyright © 2020-2023  润新知