美文网首页
HTTP客户端之OkHttp

HTTP客户端之OkHttp

作者: Tinyspot | 来源:发表于2023-11-20 10:42 被阅读0次

1. OkHttp

官网 https://square.github.io/okhttp/

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

2. 示例

2.1 GET请求

@RestController
public class HttpController {

    @RequestMapping("/get")
    public String get() {
        return "success";
    }

    @RequestMapping("/httpGet")
    public String httpGet() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://localhost:8080/get")
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

请求URL: http://localhost:8080/httpGet

2.2 POST请求

@RestController
public class HttpController {
    @PostMapping("/json")
    public String jsonAjax(@RequestBody ContextDTO contextDTO) {
        return JSON.toJSONString(contextDTO);
    }

    /**
     * json数据有两种方式可以接收:使用POJO和Map进行接收
     */
    @RequestMapping("/map")
    public String mapAjax(@RequestBody Map<String,Object> map) {
        return JSON.toJSONString(map);
    }

    private static final MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
    @RequestMapping("/httpPost")
    public String httpPost() {
        OkHttpClient client = new OkHttpClient();

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("context", "111");
        jsonObj.put("appName", "concrete");
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(mediaType, jsonObj.toJSONString());

        Request request = new Request.Builder()
                .url("http://localhost:8080/json")
                .post(requestBody)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

请求URL: http://localhost:8080/httpPost

相关文章

网友评论

      本文标题:HTTP客户端之OkHttp

      本文链接:https://www.haomeiwen.com/subject/qylvwdtx.html