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 相关文章推荐
springboot利用redis、Redisson处理并发问题的操作
Jun 18 Java/Android
详解Java实践之建造者模式
Jun 18 Java/Android
springboot如何初始化执行sql语句
Jun 22 Java/Android
eclipse创建项目没有dynamic web的解决方法
Jun 24 Java/Android
Java SSH 秘钥连接mysql数据库的方法
Jun 28 Java/Android
elasticSearch-api的具体操作步骤讲解
Jun 28 Java/Android
Spring Boot 整合 Apache Dubbo的示例代码
Jul 04 Java/Android
java设计模式--建造者模式详解
Jul 21 Java/Android
Spring Boot 排除某个类加载注入IOC的操作
Aug 02 Java/Android
Java 在生活中的 10 大应用
Nov 02 Java/Android
Springboot如何同时装配两个相同类型数据库
Nov 17 Java/Android
java.util.NoSuchElementException原因及两种解决方法
Jun 28 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
PHP脚本的10个技巧(4)
2006/10/09 PHP
PHP 的异常处理、错误的抛出及回调函数等面向对象的错误处理方法
2012/12/07 PHP
解析PHP中ob_start()函数的用法
2013/06/24 PHP
PHP 使用redis简单示例分享
2015/03/05 PHP
Yii2 GridView实现列表页直接修改数据的方法
2016/05/16 PHP
phpinfo()中Loaded Configuration File(none)的解决方法
2017/01/16 PHP
php实现解析xml并生成sql语句的方法
2018/02/03 PHP
PHP使用openssl扩展实现加解密方法示例
2020/02/20 PHP
如何在PHP环境中使用ProtoBuf数据格式
2020/06/19 PHP
PHP中-&gt;和=&gt;的含义及使用示例解析
2020/08/06 PHP
firefox 和 ie 事件处理的细节,研究,再研究 书写同时兼容ie和ff的事件处理代码
2007/04/12 Javascript
javascript parseInt 函数分析(转)
2009/03/21 Javascript
firefox firebug中文入门教程 脚本之家新年特别版
2010/01/02 Javascript
js 自制滚动条的小例子
2013/03/16 Javascript
setInterval,setTimeout与jquery混用的问题
2013/04/08 Javascript
纯JS实现根据CSS的class选择DOM
2014/03/22 Javascript
javascript定义变量时带var与不带var的区别分析
2015/01/12 Javascript
详解Bootstrap四种图片样式
2016/01/04 Javascript
如何实现json数据可视化详解
2016/11/24 Javascript
react.js 翻页插件实例代码
2017/01/19 Javascript
Angular.js与node.js项目里用cookie校验账户登录详解
2017/02/22 Javascript
在页面中引入js的两种方法(推荐)
2017/08/29 Javascript
在 Node.js 中使用原生 ES 模块方法解析
2017/09/19 Javascript
Nodejs 发布自己的npm包并制作成命令行工具的实例讲解
2018/05/15 NodeJs
深度了解vue.js中hooks的相关知识
2019/06/14 Javascript
Python多继承顺序实例分析
2018/05/26 Python
利用python-pypcap抓取带VLAN标签的数据包方法
2019/07/23 Python
Pytorch在NLP中的简单应用详解
2020/01/08 Python
关于python pycharm中输出的内容不全的解决办法
2020/01/10 Python
Python实现FLV视频拼接功能
2020/01/21 Python
python数据预处理 :数据抽样解析
2020/02/24 Python
Python利用pip安装tar.gz格式的离线资源包
2020/09/14 Python
opencv实现图像几何变换
2021/03/24 Python
前厅部经理岗位职责范文
2014/02/04 职场文书
pytorch--之halfTensor的使用详解
2021/05/24 Python
动作冒险《Hell Is Us》将采用虚幻5 消灭怪物探索王国
2022/04/13 其他游戏