Springboot HTTP如何调用其他服务

目录
  • HTTP如何调用其他服务
    • 1.GET请求
    • 2.POST请求
  • springboot请求其他服务器的http接口
    • 使用Get方式,携带headers请求数据
    • 使用Post方式,携带body请求数据

HTTP如何调用其他服务

1.GET请求

1.1Client代码

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
 
@Service
public class UserInfoClient {
    public String getUserTotalAmount(){
        Map<String,String> map=new HashMap<String,String>();
        map.put("name","123");
        map.put("password","123");
        URI uri = UriComponentsBuilder.fromHttpUrl("http://localhost:8081/spring/test")
                .queryParam("jsonString",JSON.toJSONString(map))
                .queryParam("token","12122222111")
                .build().encode().toUri();
        RestTemplate restTemplate=new RestTemplate();
        String data=restTemplate.getForObject(uri,String.class);
        System.out.println(data);
        return null;
    }
    public static void main(String[] args){
        UserInfoClient c=new UserInfoClient();
        c.getUserTotalAmount();
    }
}

1.2 Service 代码

import org.springframework.web.bind.annotation.*; 
@RestController
@RequestMapping(value = "/spring")
public class Test {
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String testSpringBoot(@RequestParam String jsonString,@RequestParam String token){
        System.out.println(jsonString);
        System.out.println(token);
        /*
         *逻辑处理
         */
        return "Spring Boot 测试成功!";
    }
}

2.POST请求

2.1Client代码

import com.alibaba.fastjson.JSON;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
 
@Service
public class UserInfoClient { 
    public String getUserTotalAmount(){
        Map<String,String> map=new HashMap<String,String>();
        map.put("name","123");
        map.put("password","123");
        String url="http://localhost:8081/spring/test";
        //设置请求头信息
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        //设置body部分
        HttpEntity<String> entity = new HttpEntity<String>(JSON.toJSONString(map),headers);
        RestTemplate restTemplate=new RestTemplate();
        ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        System.out.println(result.getBody());
        return null;
    }
    public static void main(String[] args){
        UserInfoClient c=new UserInfoClient();
        c.getUserTotalAmount();
    }
}

2.2 Service代码

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/spring")
public class Test {
    @RequestMapping(value = "/test",method = RequestMethod.POST)
    public String testSpringBoot(@RequestBody UserBean userBean){
        System.out.println(userBean);
        /*
         *逻辑处理
         */
        return "Spring Boot 测试成功!";
    }
}

springboot请求其他服务器的http接口

使用Get方式,携带headers请求数据

//注入
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/FaceInfo")
@ResponseBody
public Object   faceInfo(String startTime,String endTime,Integer size ){
    String apiURL = "http://www.05un.cn/wspp/GceGroups";
    HttpHeaders headers = new HttpHeaders();
   headers.add("userId","38");
    // headers.set("userId","38");
    headers.setContentType(MediaType.APPLICATION_JSON);
    Map<String, Object> requestParam = new HashMap<>();
    HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(requestParam, headers);
        ResponseEntity<String> entity2 = restTemplate.exchange(apiURL, HttpMethod.GET, request, String.class);
    String body = entity2.getBody();
    return body;
}

使用Post方式,携带body请求数据

//注入
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/FaceInfo")
@ResponseBody
public Object   faceInfo(String startTime,String endTime,Integer size ){
    String apiURL = "http://www.0531yun.cn/wsjc/app/Login";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    Map<String, Object> requestParam = new HashMap<>();
    requestParam.put("loginName", "jnr");
    requestParam.put("password", "jn");
    HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(requestParam, headers);
    String s=request.toString();
    ResponseEntity<String> entity2 = restTemplate.exchange(apiURL, HttpMethod.POST, request, String.class);
    String body = entity2.getBody();
    return body;
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot使用Feign调用其他服务接口

    使用SpringCloud的Feign组件能够为服务间的调用节省编码时间并提高开发效率,当服务本身不复杂时可以单独将该组件拿出使用. 引入依赖 <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign --> <dependency> <groupId>org.springframework.cloud</groupId>

  • Spring http服务远程调用实现过程解析

    最近公司有个新的需求,写了一个接口,想要把服务暴露出去,但是这个服务所在的进程是非web项目,(可以理解成schedule/batch等进程项目),所以没有tomcat等容器,而且只有这一个服务,无论是加dubbo服务还是加tomcat等容器都显得复杂了.那么应该如何将服务暴露出去? 经过网上搜索后,最终解决问题,记录在此. 为了快速搭建,使用springboot来搭建项目: 项目结构如图: 首先需要创建一个接口,服务的提供者和服务的调用方都依赖这个模块. package com.xiazhi.

  • 使用SpringBoot跨系统调用接口的方案

    一.简介 项目开发中存在系统之间互调问题,又不想用dubbo,这里提供几种springboot方案: 1.使用Feign进行消费(推荐) 2.使用原始httpClient请求 3.使用RestTemplate方法 二.方案 方案一:使用Feign进行消费(推荐) 1.在maven中添加依赖 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-st

  • spring boot中使用http请求的示例代码

    因为项目需求,需要两个系统之间进行通信,经过一番调研,决定使用http请求. 服务端没有什么好说的,本来就是使用web 页面进行访问的,所以spring boot启动后,controller层的接口就自动暴露出来了,客户端通过调用对应的url即可,所以这里主要就客户端. 首先我自定义了一个用来处理http 请求的工具类DeviceFactoryHttp,既然是url访问,那就有两个问题需要处理,一个请求服务的url,和请求服务端的参数,客户端的消息头请求服务的url:请求服务端url我定义的是跟

  • Springboot HTTP如何调用其他服务

    目录 HTTP如何调用其他服务 1.GET请求 2.POST请求 springboot请求其他服务器的http接口 使用Get方式,携带headers请求数据 使用Post方式,携带body请求数据 HTTP如何调用其他服务 1.GET请求 1.1Client代码 import com.alibaba.fastjson.JSON; import org.springframework.stereotype.Service; import org.springframework.web.clien

  • 详解SpringBoot通过restTemplate实现消费服务

    一.RestTemplate说明 RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率.前面的博客中http://www.jb51.net/article/132885.htm,已经使用Jersey客户端来实现了消费spring boot的Restful服务,接下来,我们使用RestTemplate来消费前面示例中的Restful服务,前面的示例: springboot整合H2内存

  • 传统tomcat启动服务与springboot启动内置tomcat服务的区别(推荐)

    spring整合springmvc spring整合springmvc中web.xml配置如下,tomcat在启动过程中会加载web.xml中的内容,ContextLoaderListener实现了tomcat里面的ServletContextListener接口,所以在tomcat容器启动过程通过ContextLoaderListener来进行spring容器的初始化操作,并将classpath:spring/applicationContext-*.xml指定下的spring配置文件加载,该

  • springboot 整合EhCache实现单服务缓存的操作方法

    目录 一.整合Spring Cache 与Ehcache 二.缓存的使用方法 三.缓存使用中的坑 在Spring框架内我们首选Spring Cache作为缓存框架的门面,之所以说它是门面,是因为它只提供接口层的定义以及AOP注解等,不提供缓存的具体存取操作.缓存的具体存储还需要具体的缓存存储,比如EhCache .Redis等.Spring Cache与缓存框架的关系有点像SLF4j与logback.log4j的关系. EhCache 适用于单体应用的缓存,当应用进行分布式部署的时候,各应用的副

  • SpringBoot Http远程调用的方法

    本文实例为大家分享了SpringBoot Http远程调用的具体代码,供大家参考,具体内容如下 一.在实现远程调用时可以使用feign与http远程调用,两者的关系有一下几点: feign.http,有时候在调用第三方api的时候.使用httpclient,别人的接口不可能提供它的配置,自己项目框架是spring的,使用feign相互配置,都是okhttpclient的方式.Feign是一个接口声明式调用框架,实现了一个抽象层的逻辑,没有真正实现底层http请求,提供了一个client接口用于实

  • SpringBoot整合多个Mq服务做法详解

    目录 1.自定义一个MqTemplate 2.定义一个mq配置项相对应的类 3.将我们自定义的mq配置定义成MqTemplate类型的bean 4.使用对应的Template发送消息 以rabbitmq为例 springboot项目想要整合rabbitmq非常简单,只需要在maven中引入对应的starter即可 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spri

  • ASP.NET调用WebService服务的方法详解

    本文实例讲述了ASP.NET调用WebService服务的方法.分享给大家供大家参考,具体如下: 一.WebService:WebService是以独立于平台的方式,通过标准的Web协议,可以由程序访问的应用程序逻辑单元. (1)应用程序逻辑单元:web服务包括一些应用程序逻辑单元或者代码.这些代码可以完成运算任务,可以完成数据库查询,可以完成计算机程序能够完成的任何工作. (2)可由程序访问:当前大多是web站点都是通过浏览器由人工访问的,web服务可以由计算机程序来访问. (3)标准的we协

  • jQuery实现ajax调用WCF服务的方法(附带demo下载)

    本文实例讲述了jQuery实现ajax调用WCF服务的方法.分享给大家供大家参考,具体如下: 关于AJAX调用WCF服务分为跨域和不跨域两种方式,今天咱们先介绍下不跨域下的调用方法.DEMO是在VS2008写的. 经过测试与研究,发现AJAX调用WCF服务必须满足以下条件 1.wcf的通讯方式必须使用webHttpBinding 2.必须设置<endpointBehaviors>节点的值 3.服务的实现必须添加标记 复制代码 代码如下: [AspNetCompatibilityRequirem

  • jQuery ajax调用WCF服务实例

    恩,在由瘦客户端转换成胖浏览器端的"潮流"下,必然要使用JavaScript调用后台的各种服务. 屌丝所维护的产品通信都是使用的WCF服务,因此必然要学习这样的内容.借用jQuery强大的库,使用JavaScript访问WCF服务非常简便.同事研究了一个breeze库,那么屌丝就来试验一下ajax.这里把实现简单地记录以便马克一下,以后忘了就看这篇日志来作弊. 一.更改WCF服务的配置 默认情况下,WCF服务是不允许使用HTTP请求来访问的.我们需要将WCF服务的配置文件(注意如果有其

随机推荐