java调用Restful接口的三种方法


Posted in Java/Android onAugust 23, 2021

1,基本介绍

Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多,

  本次介绍三种:

    1.HttpURLConnection实现

    2.HttpClient实现

    3.Spring的RestTemplate     

2,HttpURLConnection实现

@Controller
public class RestfulAction {

    @Autowired
    private UserService userService;
    // 修改
    @RequestMapping(value = "put/{param}", method = RequestMethod.PUT)
    public @ResponseBody String put(@PathVariable String param) {
        return "put:" + param;
    }
    // 新增
    @RequestMapping(value = "post/{param}", method = RequestMethod.POST)
    public @ResponseBody String post(@PathVariable String param,String id,String name) {
        System.out.println("id:"+id);
        System.out.println("name:"+name);
        return "post:" + param;
    }
    // 删除
    @RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)
    public @ResponseBody String delete(@PathVariable String param) {
        return "delete:" + param;
    }
    // 查找
    @RequestMapping(value = "get/{param}", method = RequestMethod.GET)
    public @ResponseBody String get(@PathVariable String param) {
        return "get:" + param;
    }
    // HttpURLConnection 方式调用Restful接口
    // 调用接口
    @RequestMapping(value = "dealCon/{param}")
    public @ResponseBody String dealCon(@PathVariable String param) {
        try {
            String url = "http://localhost:8080/tao-manager-web/";
            url+=(param+"/xxx");
            URL restServiceURL = new URL(url);
            HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL
                    .openConnection();
            //param 输入小写,转换成 GET POST DELETE PUT 
            httpConnection.setRequestMethod(param.toUpperCase());
//            httpConnection.setRequestProperty("Accept", "application/json");
            if("post".equals(param)){
                //打开输出开关
                httpConnection.setDoOutput(true);
//                httpConnection.setDoInput(true);

                //传递参数
                String input = "&id="+ URLEncoder.encode("abc", "UTF-8");
                input+="&name="+ URLEncoder.encode("啊啊啊", "UTF-8");
                OutputStream outputStream = httpConnection.getOutputStream();
                outputStream.write(input.getBytes());
                outputStream.flush();
            }
            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException(
                        "HTTP GET Request Failed with Error code : "
                                + httpConnection.getResponseCode());
            }
            BufferedReader responseBuffer = new BufferedReader(
                    new InputStreamReader((httpConnection.getInputStream())));
            String output;
            System.out.println("Output from Server:  \n");
            while ((output = responseBuffer.readLine()) != null) {
                System.out.println(output);
            }
            httpConnection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
}

3.HttpClient实现

package com.taozhiye.controller;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taozhiye.entity.User;
import com.taozhiye.service.UserService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
public class RestfulAction {  
    @Autowired
    private UserService userService;
    // 修改
    @RequestMapping(value = "put/{param}", method = RequestMethod.PUT)
    public @ResponseBody String put(@PathVariable String param) {
        return "put:" + param;
    }
    // 新增
    @RequestMapping(value = "post/{param}", method = RequestMethod.POST)
    public @ResponseBody User post(@PathVariable String param,String id,String name) {
        User u = new User();
        System.out.println(id);
        System.out.println(name);
        u.setName(id);
        u.setPassword(name);
        u.setEmail(id);
        u.setUsername(name);
        return u;
    }    
    // 删除
    @RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)
    public @ResponseBody String delete(@PathVariable String param) {
        return "delete:" + param;
    }
    // 查找
    @RequestMapping(value = "get/{param}", method = RequestMethod.GET)
    public @ResponseBody User get(@PathVariable String param) {
        User u = new User();
        u.setName(param);
        u.setPassword(param);
        u.setEmail(param);
        u.setUsername("爱爱啊");
        return u;
    }
    @RequestMapping(value = "dealCon2/{param}")
    public @ResponseBody User dealCon2(@PathVariable String param) {
        User user = null;
        try {
            HttpClient client = HttpClients.createDefault();
            if("get".equals(param)){
                HttpGet request = new HttpGet("http://localhost:8080/tao-manager-web/get/"
                        +"啊啊啊");
                request.setHeader("Accept", "application/json");
                HttpResponse response = client.execute(request);
                HttpEntity entity = response.getEntity();
                ObjectMapper mapper = new ObjectMapper();
                user = mapper.readValue(entity.getContent(), User.class);
            }else if("post".equals(param)){
                HttpPost request2 = new HttpPost("http://localhost:8080/tao-manager-web/post/xxx");
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
                nvps.add(new BasicNameValuePair("id", "啊啊啊"));  
                nvps.add(new BasicNameValuePair("name", "secret"));
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, "GBK");
                request2.setEntity(formEntity);
                HttpResponse response2 = client.execute(request2);
                HttpEntity entity = response2.getEntity();
                ObjectMapper mapper = new ObjectMapper();
                user = mapper.readValue(entity.getContent(), User.class);
            }else if("delete".equals(param)){

            }else if("put".equals(param)){

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    } 
}

4.Spring的RestTemplate

springmvc.xml增加

<!-- 配置RestTemplate -->
    <!--Http client Factory -->
    <bean id="httpClientFactory"
        class="org.springframework.http.client.SimpleClientHttpRequestFactory">
        <property name="connectTimeout" value="10000" />
        <property name="readTimeout" value="10000" />
    </bean>

    <!--RestTemplate -->
    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <constructor-arg ref="httpClientFactory" />
    </bean>

controller

@Controller
public class RestTemplateAction {

    @Autowired
    private RestTemplate template;

    @RequestMapping("RestTem")
    public @ResponseBody User RestTem(String method) {
        User user = null;
        //查找
        if ("get".equals(method)) {
            user = template.getForObject(
                    "http://localhost:8080/tao-manager-web/get/{id}",
                    User.class, "呜呜呜呜");

            //getForEntity与getForObject的区别是可以获取返回值和状态、头等信息
            ResponseEntity<User> re = template.
                    getForEntity("http://localhost:8080/tao-manager-web/get/{id}",
                    User.class, "呜呜呜呜");
            System.out.println(re.getStatusCode());
            System.out.println(re.getBody().getUsername());

        //新增
        } else if ("post".equals(method)) {
            HttpHeaders headers = new HttpHeaders();
            headers.add("X-Auth-Token", UUID.randomUUID().toString());
            MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
            postParameters.add("id", "啊啊啊");
            postParameters.add("name", "部版本");
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
                    postParameters, headers);
            user = template.postForObject(
                    "http://localhost:8080/tao-manager-web/post/aaa", requestEntity,
                    User.class);
        //删除
        } else if ("delete".equals(method)) {
            template.delete("http://localhost:8080/tao-manager-web/delete/{id}","aaa");
        //修改
        } else if ("put".equals(method)) {
            template.put("http://localhost:8080/tao-manager-web/put/{id}",null,"bbb");
        }
        return user;

    }
}

到此这篇关于java调用Restful接口的三种方法的文章就介绍到这了,更多相关java调用Restful接口内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Java/Android 相关文章推荐
为什么在foreach循环中JAVA集合不能添加或删除元素
Jun 11 Java/Android
springboot利用redis、Redisson处理并发问题的操作
Jun 18 Java/Android
SpringBoot 拦截器妙用你真的了解吗
Jul 01 Java/Android
dubbo服务整合zipkin详解
Jul 26 Java/Android
Java数据开发辅助工具Docker与普通程序使用方法
Sep 15 Java/Android
Java 垃圾回收超详细讲解记忆集和卡表
Apr 08 Java/Android
Android自定义双向滑动控件
Apr 19 Java/Android
Elasticsearch Recovery 详细介绍
Apr 19 Java/Android
JAVA springCloud项目搭建流程
May 11 Java/Android
Qt数据库应用之实现图片转pdf
Jun 01 Java/Android
Spring Cloud OpenFeign模版化客户端
Jun 25 Java/Android
SpringBoot Http远程调用的方法
Aug 14 Java/Android
JVM钩子函数的使用场景详解
Java中CyclicBarrier和CountDownLatch的用法与区别
Aug 23 #Java/Android
SpringBoot整合Mybatis Generator自动生成代码
Aug 23 #Java/Android
Java面试题冲刺第十九天--数据库(4)
Java获取e.printStackTrace()打印的信息方式
Aug 07 #Java/Android
Java移除无效括号的方法实现
Aug 07 #Java/Android
简述Java中throw-throws异常抛出
Aug 07 #Java/Android
You might like
解析dedeCMS验证码的实现代码
2013/06/07 PHP
PHP中rename()函数的妙用讲解
2019/02/28 PHP
jquery 表单进行客户端验证demo
2009/08/24 Javascript
利用jQuery插件扩展识别浏览器内核与外壳的类型和版本的实现代码
2011/10/22 Javascript
纯文字版返回顶端的js代码
2013/08/01 Javascript
jquery div拖动效果示例代码
2013/12/08 Javascript
javascript学习笔记--数字格式类型
2014/05/22 Javascript
javascript实现点击单选按钮链接转向对应网址的方法
2015/08/12 Javascript
JavaScript禁止复制与粘贴的实现代码
2016/05/16 Javascript
jquery对所有input type=text的控件赋值实现方法
2016/12/02 Javascript
Javascript 两种刷新方法以及区别和适用范围
2017/01/17 Javascript
详解微信小程序入门从这里出发(登录注册、开发工具、文件及结构介绍)
2020/07/21 Javascript
[59:42]Secret vs Alliacne 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
Python ljust rjust center输出
2008/09/06 Python
python中的字典详细介绍
2014/09/18 Python
python sort、sorted高级排序技巧
2014/11/21 Python
Python使用PDFMiner解析PDF代码实例
2017/03/27 Python
用Django实现一个可运行的区块链应用
2018/03/08 Python
python贪婪匹配以及多行匹配的实例讲解
2018/04/19 Python
Python爬取数据保存为Json格式的代码示例
2019/04/09 Python
Python实现EXCEL表格的排序功能示例
2019/06/25 Python
Python实现的ftp服务器功能详解【附源码下载】
2019/06/26 Python
Django后端接收嵌套Json数据及解析详解
2019/07/17 Python
Pycharm连接远程服务器过程图解
2020/04/30 Python
美国最大的团购网站:Groupon
2016/07/23 全球购物
联想墨西哥官方网站:Lenovo墨西哥
2016/08/17 全球购物
美国高级音响品牌:Master&Dynamic
2018/07/05 全球购物
医校毕业生自我鉴定
2014/01/25 职场文书
出纳员岗位职责
2014/03/13 职场文书
教师个人自我评价范文
2014/04/13 职场文书
2014年国庆节演讲稿精选范文1500字
2014/09/25 职场文书
英文感谢信格式
2015/01/21 职场文书
打架检讨书
2015/01/27 职场文书
教代会开幕词
2015/01/28 职场文书
Nginx 502 bad gateway错误解决的九种方案及原因
2022/08/14 Servers
javascript中Set、Map、WeakSet、WeakMap区别
2022/12/24 Javascript