Http请求接口

方法一、使用springboot框间自带的Http的工具类RestTemplate。

RestTemplate为springframework中自带的处理Http的工具类。

具体用法

请求的接口

@RestController
@RequestMapping("/index")
public class MyController { 
@PostMapping("/testPost")
    public Map<String, Object> testPost(@RequestBody Map map) {
        Map<String, Object> mm = new HashMap<>();
        mm.put("学号", map.get("sno"));
        mm.put("姓名", map.get("sname"));
        mm.put("年龄", map.get("age"));
        mm.put("性别", map.get("sex"));
        mm.put("班级", map.get("sclass"));
        return mm;
    }

    @GetMapping("/testGet")
    public Student testGet(@RequestParam String sno,
                           @RequestParam String sname,
                           @RequestParam String age,
                           @RequestParam String sex,
                           @RequestParam String sclass) {
        Student student = new Student(Integer.parseInt(sno), sname, Integer.parseInt(age), sex, sclass);
        return student;
    }

}

Get和Post请求

@Test
    public void testExchange_post() {
        Student student = new Student(20160004, "李四", 20, "男", "2016222");
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        //headerName必须是英文,headerValue可以有中文
        //请求头会封装一些像token这些信息,用于作为调接口的鉴权
        httpHeaders.add("studentInfo", "个人信息");
        HttpEntity<Student> httpEntity = new HttpEntity<>(student, httpHeaders);
        System.out.println("httpEntity的请求头为:" + httpEntity.getHeaders());
        System.out.println("httpEntity的请求体为:" + httpEntity.getBody());
        ResponseEntity<Map> responseEntity = restTemplate.exchange("http://localhost:8080/index/testPost", HttpMethod.POST, httpEntity, Map.class);
        System.out.println("返回的请求头为:" + responseEntity.getHeaders());
        System.out.println("返回的请求体为:" + responseEntity.getBody());
    }

    @Test
    public void testExchange_get() {
        Student student = new Student(20160004, "李四", 20, "男", "2016222");
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        //headerName必须是英文,headerValue可以有中文
        httpHeaders.add("cookie", "cookie");
        HttpEntity<Student> httpEntity = new HttpEntity<>(null, httpHeaders);
        System.out.println("httpEntity的请求头为:" + httpEntity.getHeaders());
        System.out.println("httpEntity的请求体为:" + httpEntity.getBody());
        Map<String, Object> map = new HashMap<>();
        ResponseEntity<Student> responseEntity = restTemplate.
                exchange("http://localhost:8080/index/testGet?sno={sno}&sname={sname}&age={age}&sex={sex}&sclass={sclass}",
                        HttpMethod.GET, httpEntity, Student.class, student.getSno(), student.getSname(), student.getAge(), student.getSex(), student.getSclass());
        System.out.println("返回的请求头为:" + responseEntity.getHeaders());
        System.out.println("返回的请求体为:" + responseEntity.getBody());
    }

方法二、使用apache的httpclient工具类

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

 @Test
    public void testHttpClient_get() throws URISyntaxException, IOException {
        // 获得Http客户端
        HttpClient httpClient = HttpClientBuilder.create().build();
        Student student = new Student(20160004, "李四", 20, "男", "2016222");
        // 将参数放入键值对类NameValuePair中,再放入集合中
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("sno", String.valueOf(student.getSno())));
        params.add(new BasicNameValuePair("sname", student.getSname()));
        params.add(new BasicNameValuePair("age", String.valueOf(student.getAge())));
        params.add(new BasicNameValuePair("sex", student.getSex()));
        params.add(new BasicNameValuePair("sclass", student.getSclass()));
        URI uri = new URIBuilder().setScheme("http").setHost("localhost")
                .setPort(8080).setPath("/index/testGet")
                .setParameters(params).build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet(uri);
        // 响应模型
        HttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();
            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            org.apache.http.HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } finally {
//            try {
//                // 释放资源
//                if (httpClient != null) {
//                    httpClient.close();
//                }
//                if (response != null) {
//                    response.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            //CloseableHttpClient  HttpClient  HttpResponse  HttpServletResponse
        }
    }

    @Test
    public void testHttpClient_post() throws URISyntaxException, IOException {
        // 获得Http客户端
        HttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost("http://localhost:8080/index/testPost");
        Student student = new Student(20160004, "李四", 20, "男", "2016222");
        // 我这里利用阿里的fastjson,将Object转换为json字符串;
        // (需要导入com.alibaba.fastjson.JSON包)
        String jsonString = JSON.toJSONString(student);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        // 响应模型
        HttpResponse response = null;
        HttpServletResponse httpServletResponse = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            org.apache.http.HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            try {
//                // 释放资源
//                if (httpClient != null) {
//                    httpClient.close();
//                }
//                if (response != null) {
//                    response.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
    }

参考资料

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金斗潼关

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值