• Springboot笔记-有header的post请求、get请求


    1、post请求过程中,header中的身份信息怎么加进去并传输?

    首先写一个基础方法 send ,将header信息填写进来

    package com.boc.web;
    
    import java.io.IOException;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;
    
    import com.alibaba.fastjson.JSONObject;
    import com.sun.el.parser.ParseException;
    
    public class PostSend {
    
    	   public static String send(String url, JSONObject jsonObject, String encoding) throws ParseException, IOException {
    		      String body = "";
    		 
    		      //创建httpclient对象
    		      CloseableHttpClient client = HttpClients.createDefault();
    		      //创建post方式请求对象
    		      HttpPost httpPost = new HttpPost(url);
    		 
    		      //装填参数
    		      StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
    		      s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    		      //设置参数到请求对象中
    		      httpPost.setEntity(s);
    		      System.out.println("请求地址:" + url);
    //		        System.out.println("请求参数:"+nvps.toString());
    		 
    		      //设置header信息
    		      //指定报文头【Content-type】、【User-Agent】
    //		        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
    		      httpPost.setHeader("Content-type", "application/json");
    		      httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    		      
    		      httpPost.addHeader("clientId","****************");
    		      httpPost.addHeader("clientSecret","****************");
    		      httpPost.addHeader("grantType","***************");
    		      //执行请求操作,并拿到结果(同步阻塞)
    		      CloseableHttpResponse response = client.execute(httpPost);
    		      //获取结果实体
    		      HttpEntity entity = response.getEntity();
    		      if (entity != null) {
    		         //按指定编码转换结果实体为String类型
    		         body = EntityUtils.toString(entity, encoding);
    		      }
    		      EntityUtils.consume(entity);
    		      //释放链接
    		      response.close();
    		      return body;
    		 
    		   }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    然后就可以在create中调用该方法了

    	@ResponseBody
    	@GetMapping("/create")
    	public String create(@RequestParam("poolname") String poolname, @RequestParam("phonenum") String phonenum) 
    			throws ParseException {
    		
    		//list格式的"phones"字段封装成json数组:enclosure
    		String data = null;
    		ArrayList<HashMap<String, String>> enclosureList = new ArrayList<HashMap<String, String>>();
    		HashMap<String, String> tmpHash = new HashMap<String, String>();
    		tmpHash.put("phone", phonenum);
    		enclosureList.add(tmpHash);
    		JSONArray enclosure = JSONArray.parseArray(JSON.toJSONString(enclosureList));
    		
    		//创建号码池URL
    		String url = "https://*****************************";
    		
    		//Json对象存储访问参数
    		JSONObject jsonParam = new JSONObject();
    		jsonParam.put("name", poolname);
    		jsonParam.put("callCondition", "voice_upload");
    		jsonParam.put("phoneDecryption", "asccode");
    		jsonParam.put("phones", enclosure);
    
    		try {		
    			//调用post请求方式
    			data = PostSend.send(url, jsonParam, "UTF-8");
    		} 
    		catch (IOException e) {
    			e.printStackTrace();
    		}
    
    		return data;
    
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    接下来详解一下create方法,主要分成三大部分,下面逆序讲解

    (3)服务器方要求:post访问中,body设置json格式。

    		{
    		    "name":"Test1",
    		    "callCondition":"voice_upload",
    		    "phoneDecryption":"asccode",
    		    "phones":[
    		        {
    		            "phone":"188000000"
    		        }
    		    ]
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在这里插入图片描述

    因此需要将数据都存储成json对象。

    		//Json对象存储访问参数
    		JSONObject jsonParam = new JSONObject();
    		jsonParam.put("name", poolname);
    		jsonParam.put("callCondition", "voice_upload");
    		jsonParam.put("phoneDecryption", "asccode");
    		jsonParam.put("phones", enclosure);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    jsonParam.put 要求输入是String类型的键值对,如“callCondition”, “voice_upload”“phoneDecryption”, “asccode”。而 poolname 是接收的前端 index.html 传输过来的字符,因此需要在方法中填写参数:

    public String create(@RequestParam("poolname") String poolname, @RequestParam("phonenum") String phonenum) 
    			throws ParseException {
    
    • 1
    • 2

    同理,phonenum 也是同样利用前端传递获得的,只不过与 poolname 略有不同,见下

    (2)观察发现,前三个参数都是一对一String键值对,而 phonenum 是List的map型,因此需要通过下述方法整合成json数组

    	 "phones":[
    			        {
    			            "phone":"188000000"
    			        }
    			    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    		//list格式的"phones"字段封装成json数组:enclosure
    		String data = null;
    		ArrayList<HashMap<String, String>> enclosureList = new ArrayList<HashMap<String, String>>();
    		HashMap<String, String> tmpHash = new HashMap<String, String>();
    		tmpHash.put("phone", phonenum);
    		enclosureList.add(tmpHash);
    		JSONArray enclosure = JSONArray.parseArray(JSON.toJSONString(enclosureList));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    (1)然后可调用前面的 send 方法了

    data = PostSend.send(url, jsonParam, "UTF-8");
    
    • 1

    参考文章

    2、get请求过程中,header中的身份信息怎么加进去并传输?

    首先写一个基础方法 send ,将header信息填写进来

    package com.boc.web;
    
    import java.util.Arrays;
    
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.client.RestTemplate;
    
    public class GetSend {
    	// ************ GET ***************
    	/**
    	 * Spring Boot Get请求
    	 */
    	public static ResponseEntity<String> getsend(String url) {
    
    		RestTemplate restTemplate = new RestTemplate();
    		HttpHeaders headers = new HttpHeaders();
    		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    		headers.add("clientId", "*****************");
    		headers.add("clientSecret", "**********************");
    		headers.add("grantType", "************************");
    		HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
    		ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    
    		return result;
    	}
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    然后就可以在 taskprocess 中调用该方法了

    	@ResponseBody
    	@RequestMapping("/taskprocess")
    	public ResponseEntity<String> taskprocess(@RequestParam("taskid") String taskid) 
    			throws ParseException {
    		ResponseEntity<String> data = null;
    		
    		//外呼进度查询URL
    		String url = "https://robot.wewecall.com/callout-adapter/adapter/tasks/process/" + taskid;
    		
    		//调用get请求方式
    		data = GetSend.getsend(url);
    
    		return data;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    与post相同的原理, taskid 通过前端传入获取。

    备注:
    pox.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>2.3.1.RELEASE</version>
    		<relativePath/> <!-- lookup parent from repository -->
    	</parent>
    	<groupId>com.boc</groupId>
    	<artifactId>start</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>start</name>
    	<description>Start project for Spring Boot</description>
    	<properties>
    		<java.version>1.8</java.version>
    	</properties>
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    
    		<dependency>
    		    <groupId>org.springframework.boot</groupId>
    		    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.bouncycastle</groupId>
    			<artifactId>bcprov-jdk15on</artifactId>
    			<version>1.69</version>
    		</dependency>
    
    		<dependency>
    		    <groupId>org.apache.commons</groupId>
    		    <artifactId>commons-lang3</artifactId>
    		    <version>3.9</version>
    		</dependency>
            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
                <version>1.11</version>
            </dependency>
    		
    		
    		<!--Alijson插件-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.54</version>
    </dependency>
    		
    		
    		  <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.3.3</version>
            </dependency>
    		
    		
    		<!--集成mysql数据库-->
    	<dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.30</version><!--$NO-MVN-MAN-VER$-->
                <scope>runtime</scope>
            </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!--lombok注解简化代码-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    
    
    
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>
    
    </project>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
  • 相关阅读:
    聚观早报 |  iPhone 14 系列正式发布;腾讯增持育碧股票至9.99%
    【Java基础面试十五】、 说一说你对多态的理解
    亚马逊国际按关键字搜索商品 API 返回值说明
    LeetCode 双周赛 103(2023/04/29)区间求和的树状数组经典应用
    前端的简单介绍
    页面置换算法的模拟实现及命中率对比
    如何进行数据结构的设计和实现?
    Android WebSocket长连接的实现
    公会晋升计划第 2 季来啦!
    序列化--Serial
  • 原文地址:https://blog.csdn.net/qq_41749451/article/details/126138857