okHttp3

2019-08-12  本文已影响0人  荒天帝886

https://www.cnblogs.com/w-bb/articles/8459727.html
git源码

一、依赖

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

二、示例

package com.fzy.javastudy.java.day_0812;

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class OkMainTest {

    private static final MediaType APPLICATION_JSON = MediaType.parse("application/json; charset=utf-8");
    private static final String PREFIX = "http://localhost:9000/day_0812/";
    private static final OkHttpClient ohc = new OkHttpClient();
    private static final ObjectMapper om = new ObjectMapper();

    /**
     * get
     * get请求
     *
     * @throws IOException
     */
    @Test
    public void get() throws IOException {
        Request request = new Request.Builder()
                .url(PREFIX + "get")
                .build();
        Call call = ohc.newCall(request);
        Response response = call.execute();
        String resStr = response.body().string();
        System.out.println(resStr);
    }

    /**
     * post
     * 表单请求
     *
     * @throws IOException
     */
    @Test
    public void post() throws IOException {
        RequestBody requestBody = new FormBody.Builder()
                .add("numA", "34")
                .add("numB", "56")
                .build();
        Request request = new Request.Builder()
                .url(PREFIX + "post")
                .post(requestBody)
                .build();
        Call call = ohc.newCall(request);
        Response response = call.execute();
        String resStr = response.body().string();
        System.out.println(resStr);
    }

    /**
     * put
     * json请求
     *
     * @throws IOException
     */
    @Test
    public void put() throws IOException {
        Map<String, Integer> params = new HashMap<>();
        params.put("numA", 10);
        params.put("numB", 45);
        String paramsJson = om.writeValueAsString(params);
        RequestBody requestBody = RequestBody.create(APPLICATION_JSON, paramsJson);
        Request request = new Request.Builder()
                .url(PREFIX + "json")
                .put(requestBody) //post(requestBody)
                .build();
        Call call = ohc.newCall(request);
        Response response = call.execute();
        String resStr = response.body().string();
        System.out.println(resStr);
    }
}

上一篇 下一篇

猜你喜欢

热点阅读