okhttp使用

okhttp使用

前期准备

  1. 引入对应的jar包
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.0.1</version>
</dependency>

post请求

@Test
public void test3() {
    MediaType JSON
            = MediaType.get("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();
    JSONObject json = new JSONObject();
    json.put("ledger", "22");
    RequestBody body = RequestBody.create(JSON, json.toJSONString());
    Request request = new Request.Builder()
            .url("http://localhost/cost-test-service/testGet")
            .post(body)
            .build();
    try (Response response = client.newCall(request).execute()) {
        System.out.println("##result##" + response.body().string());
    } catch (Exception e) {

    }
}

登录后发送post请求

//登录后存储cooki到文件
@Test
    public void test5() throws Exception {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.cookieJar(new CookieJar() {
            private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();

            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                Map<String, Object> map = new HashMap<>();

                int i = 0;

                for (Cookie cookie : cookies) {

                    System.out.println("name:" + cookie.name() + "    value:" + cookie.value());
                    map.put(cookie.name(), cookie.value());

                }

                try {
                    saveToFile(map);
                } catch (Exception e) {
                    System.out.println("序列化出现异常");
                }

                System.out.println("cookies#" + JSONObject.toJSONString(cookies.size()));
                cookieStore.put(url.host(), cookies);
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url.host());
                System.out.println("cookies1#" + JSONObject.toJSONString(cookies));
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        });
        OkHttpClient client = builder.build();
        final MediaType JSON
                = MediaType.get("application/json; charset=utf-8");

//        OkHttpClient client = new OkHttpClient();

        String url = "http://localhost/login";
        Map<String, String> map = new HashMap<>();
        map.put("key", "10");
        map.put("authType", "pwd");
        map.put("userName", "test");
        map.put("userPwd",
                "AE005C33C768E5A07C0B309FAC82438F3BF85339C50B6694C64EF72B1A2FDF60FC9088FDB0BEC4095E8785DF06D4D89D93EF4FA7F1CCC0347F9CB0EE1A7FC700C344F887D6BB52FDFE9F2B4673A57CEB73A8CDC0AC6A01EE0227BB0DF74AE2654A4F62B234E389F2E8C746");
        RequestBody body = RequestBody.create(JSON, JSONObject.toJSONString(map));
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Referer", "http://localhost/?v=" + new Date().getTime())
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            System.out.println(JSONObject.toJSONString(response.body().string()));
        }


//        try (Response response = client.newCall(request).execute()) {
//            System.out.println(JSONObject.toJSONString( response.body().string()));
//        }
    }
//存储cookie到a.txt中
public void saveToFile(Map<String, Object> cookies) throws Exception {
    File f = new File("a.txt");
    BufferedWriter out = new BufferedWriter(new FileWriter(f));
    out.write(JSONObject.toJSONString(cookies));
    out.close();

}
//从文件中读取存储的cookie信息
public JSONObject readFromFile() throws Exception {
    File f = new File("a.txt");
    BufferedReader br = new BufferedReader(new FileReader(f));
    String lineTxt = "";
    String readLine;
    while ((readLine = br.readLine()) != null) {
        lineTxt += readLine;
    }
    System.out.println(lineTxt);
    JSONObject jsonObject;
    if (StringUtils.isEmpty(lineTxt)) {
        jsonObject = new JSONObject();
    } else {

        jsonObject = JSONObject.parseObject(lineTxt);
    }
    br.close();
    return jsonObject;

}
   //使用刚才存储的文件进行请求验证
   @Test
    public void test6() throws Exception {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.cookieJar(new CookieJar() {
            private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();

            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                Map<String, Object> map = new HashMap<>();

                int i = 0;

                for (Cookie cookie : cookies) {

                    System.out.println("name:" + cookie.name() + "    value:" + cookie.value());
                    map.put(cookie.name(), cookie.value());

                }


                System.out.println("cookies#" + JSONObject.toJSONString(cookies.size()));
                cookieStore.put(url.host(), cookies);
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url.host());
                cookies = cookies != null ? cookies : new ArrayList<Cookie>();
                try {
                    JSONObject json = readFromFile();
                    if (!json.isEmpty()) {
                        Set keys = json.keySet();
                        for (Object key : keys) {
                            Cookie cookie = new Cookie.Builder().name((String) key).value(json.getString((String) key)).domain(url.host()).build();
//                            Cookie cookie = new Cookie(key,json.getString((String)key),new Date().getTime()+1000000L,"","/");
                            cookies.add(cookie);
//                            Cookie cookie=CookieJar.
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("cookies1#" + JSONObject.toJSONString(cookies));
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        });
        OkHttpClient client = builder.build();
        final MediaType JSON
                = MediaType.get("application/json; charset=utf-8");

//        OkHttpClient client = new OkHttpClient();

        String url = "http://localhost/cost-test-service/queryList";
        Map<String, String> map = new HashMap<>();
        map.put("key", "10");
        String param = "{\"currentPage\":1,\"pageSize\":6}";
        RequestBody body = RequestBody.create(JSON, param);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Referer", "http://localhost")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            System.out.println(JSONObject.toJSONString(response.body().string()));
        }

    }

get请求

    @Test
    public void testtms()  throws   Exception{
        OkHttpClient client = new OkHttpClient();
        File f = new File("b.txt");
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String readLine;
        int i=0;;
        while ((readLine = br.readLine()) != null) {
            System.out.print(++i+"deptId#"+readLine+"#");
            if(i%50==0){
                Thread.sleep(1000);
            }
            Request request = new Request.Builder()
                    .url("http://localhost/cost-test-service/dept?orgId="+readLine)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                String string = response.body().string();

                System.out.println(string);
            } catch (Exception e) {

            }



        }

}

参考:

  • https://www.jianshu.com/p/da4a806e599b
  • https://square.github.io/okhttp/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值