zoukankan      html  css  js  c++  java
  • 【java】get、post请求的远程调用

    POST的调用

    public String sendPostRequest() {
        //请求路径
        String inputHost = "http://172.0.0.1:8080/user/getUser";
        //请求报文
        String inputMessage = "{"name":"张三","age":"22"}";
        RestTemplate client = new RestTemplate();
        //新建Http头,add方法可以添加参数
        HttpHeaders headers = new HttpHeaders();
        //设置请求发送方式
        HttpMethod method = HttpMethod.POST;
        //以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_JSON);
        List<MediaType> list = new ArrayList<>();
        list.add(MediaType.APPLICATION_JSON_UTF8);
        headers.setAccept(list);
        //token修改下
        headers.set("Authorization", "token");
        //将请求头部和参数合成一个请求
        HttpEntity<String> requestEntity = new HttpEntity<>(inputMessage, headers);
        //执行HTTP请求,将返回的结构使用String 类格式化(可设置为对应返回值格式的类)
        ResponseEntity<String> response = client.exchange(inputHost, method, requestEntity, String.class);
        //返回报文
        String outputMessage = response.getBody();
        return outputMessage;
    }

    GET的调用(未测试)

    public String sendGetRequest(String url, Object message) {
        //请求路径
        String inputHost = "http://172.0.0.1:8080/user/getUser";
        //请求报文
        String inputMessage = "{"name":"张三","age":"22"}";
        RestTemplate client = new RestTemplate();
        HttpMethod method = HttpMethod.GET;
        //新建Http头,add方法可以添加参数
        HttpHeaders headers = new HttpHeaders();
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity<String> requestEntity = new HttpEntity<>(inputMessage, headers);
        //执行HTTP请求,将返回的结构使用String 类格式化
        ResponseEntity<String> response = client.exchange(inputHost, method, requestEntity, String.class);
        //返回报文
        String outputMessage = response.getBody();
    
        return outputMessage;
    }

    持续更新!!!

  • 相关阅读:
    [转] HashMap的工作原理
    [原创] hadoop学习笔记:hadoopWEB监控
    [编辑] 分享一些java视频
    [原创]spring学习笔记:关于springsource-tool-suite插件的安装
    [原创]安装Oracle 11gR2,以及如何在win8下使用plsql develper连接Oracle数据库 ,在这里和大家分享下
    dedecms _ 当前位置问题的代码
    form表单验证
    input 不支持HTML5的placeholder属性
    Dede文章列表
    DEDE首页调用{dede:field.content/}
  • 原文地址:https://www.cnblogs.com/flyinghome/p/13655808.html
Copyright © 2011-2022 走看看