HttpClient、okhttp3 简单示例

1、HttpClient

maven 依赖

<!---文件上传-->
       <dependency>
           <groupId>org.apache.httpcomponents</groupId>
           <artifactId>httpmime</artifactId>
           <version>4.5.3</version>
       </dependency>
       <!-- OKHttp3依赖 -->
       <dependency>
           <groupId>com.squareup.okhttp3</groupId>
           <artifactId>okhttp</artifactId>
           <version>3.8.1</version>
       </dependency>

公共

    String url = "http://127.0.0.1:8001/";
    CloseableHttpClient client = HttpClientBuilder.create().build();
    /*   Ok httpclient */

    private OkHttpClient okclient = new OkHttpClient.Builder().connectTimeout(60,
            TimeUnit.SECONDS).build();

测试程序

 /*   httpclient */

    @Test
    public void testPut() throws IOException {
        HttpPut httpPut = new HttpPut(url + "Put");
        HashMap<Object, Object> map = new HashMap<>(1);
        map.put("msgBody", "test post request");
        httpPut.setHeader("Content-Type", "application/json;charset=utf-8");
        CloseableHttpResponse execute = client.execute(httpPut);
        System.out.println(EntityUtils.toString(execute.getEntity()));

    }

    @Test
    public void testUpload() throws IOException {

        HttpPost httpPost = new HttpPost(url + "upload");

        File file = new File("C:\\Users\\Administrator\\Desktop\\AOP.pdf");

        FileBody body = new FileBody(file);

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        entityBuilder.addPart("file", body);
        HttpEntity build = entityBuilder.build();

        httpPost.setEntity(build);
        CloseableHttpResponse execute = client.execute(httpPost);
        System.out.println(EntityUtils.toString(execute.getEntity()));
    }

    @Test
    public void testDelete() throws IOException {
        HttpDelete httpDelete = new HttpDelete(url + "delete");
        CloseableHttpResponse execute = client.execute(httpDelete);
        System.out.println(EntityUtils.toString(execute.getEntity()));
    }

    @Test
    public void testGet() throws IOException {
        HttpGet httpGet = new HttpGet(url + "test");
        CloseableHttpResponse execute = client.execute(httpGet);

        HttpEntity entity = execute.getEntity();
        String s = EntityUtils.toString(entity);

        System.out.println(s);
    }

    @Test
    public void testPost() throws IOException {

        HttpPost httpPost = new HttpPost(url + "post");
        HashMap<Object, Object> map = new HashMap<>(1);
        map.put("msgBody", "test post request");
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

        String jsonString = JSONObject.toJSONString(map);

        httpPost.setEntity(new StringEntity(jsonString, "UTF-8"));

        CloseableHttpResponse execute = client.execute(httpPost);

        String string = EntityUtils.toString(execute.getEntity());
        System.out.println(string);
    }

2、OKHttpClient

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>
        <!-- OKHttp3依赖 -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.8.1</version>
        </dependency>

测试程序

    @Test
    public void okClientCancel() throws IOException {
        Request request = new Request.Builder()
                .url(url + "delete")
                .delete()
                .build();
        Call call = okclient.newCall(request);
        Response execute = call.execute();

        long cntTime = System.currentTimeMillis();
        while (true) {
            if (System.currentTimeMillis() - cntTime > 1000) {
                call.cancel();
                System.out.println("request cancel");
                break;
            }
        }
        System.out.println(execute.body().string());
    }

    @Test
    public void okClientUpload() throws IOException {
        MultipartBody file = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "C:\\Users\\Administrator\\Desktop\\AOP.pdf"
                        , RequestBody.create(MediaType.parse("multipart/form-data"),
                                new File("C:\\Users\\Administrator\\Desktop\\AOP.pdf")))
                .build();
        Request request = new Request.Builder()
                .url(url + "upload")
                .post(file)
                .build();
        Call call = okclient.newCall(request);
        Response execute = call.execute();
        System.out.println(execute.body().string());
    }

    @Test
    public void okClientDelete() throws IOException {
        Request request = new Request.Builder()
                .url(url + "delete")
                .delete()
                .build();
        Call call = okclient.newCall(request);
        Response execute = call.execute();
        System.out.println(execute.body().string());
    }

    @Test
    public void okClientPost() throws IOException {
        HashMap<String, Object> map = new HashMap<>(1);
        map.put("msgBody", "v1");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), JSONObject.toJSONString(map));
        Request request = new Request.Builder()
                .url(url + "post")
                .post(requestBody)
                .build();

        Call call = okclient.newCall(request);
        Response execute = call.execute();
        System.out.println(execute.body().string());
    }

    @Test
    public void okClientGet() throws IOException {
        Request request = new Request.Builder()
                .url(url + "get")
                .get()
                .build();

        Call call = okclient.newCall(request);
        Response execute = call.execute();
        System.out.println(execute.body().string());
    }

3、服务端

@RestController
public class TestGui {

    @PostMapping("upload")
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        return originalFilename;
    }

    @PostMapping("post")
    public String api(@RequestBody Data msgBody) {
        System.out.println("-> " + msgBody.toString());
        return msgBody.toString();
    }

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

    @RequestMapping("Put")
    public String Put() {
        return "Put";
    }

    @DeleteMapping("delete")
    public String delete() {
        return "delete";
    }

}

class Data {
    private String msgBody;

    public String getMsgBody() {
        return msgBody;
    }

    public void setMsgBody(String msgBody) {
        this.msgBody = msgBody;
    }

    @Override
    public String toString() {
        return "msgBody=" + msgBody;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OkHttp是一个开源的HTTP客户端库,用于发送和接收HTTP请求。它提供了一系列易于使用的方法来创建和配置HTTP客户端。下面是一些关于OkHttp的常见用法: 1. 创建OkHttpClient实例:可以使用默认的构造函数来创建一个默认配置的OkHttpClient实例,也可以使用OkHttpClient.Builder()方法来逐步配置一个OkHttpClient实例,还可以使用现有实例的newBuilder()方法进行构造。例如,可以使用以下代码创建一个默认配置的OkHttpClient实例: ``` OkHttpClient client = new OkHttpClient(); ``` 2. 发送POST请求:OkHttp也可以通过POST方式将键值对数据发送到服务器。可以使用FormBody.Builder()方法创建一个表单数据的RequestBody,然后将其添加到Request.Builder()中的post()方法中。以下是一个示例代码: ``` OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody formBody = new FormBody.Builder() .add("platform", "android") .add("name", "bug") .add("subject", "XXXXXXXXXXXXXXX") .build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } } ``` 3. 设置和读取HTTP头部:可以使用Request.Builder()的header()方法来设置HTTP请求的头部信息,使用response.header()方法来读取响应的头部信息。 综上所述,OkHttp是一个功能强大的HTTP客户端库,可以用于发送和接收HTTP请求。它提供了灵活的配置选项和简洁易用的接口,使得使用HTTP变得更加便捷。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [HTTP客户端连接,选择HttpClient还是OkHttp](https://blog.csdn.net/Dome_/article/details/103977308)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [HttpClient、OKhttp、RestTemplate对比](https://blog.csdn.net/cristianoxm/article/details/120943347)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值