IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> 使用HTTP方式发送请求及json数据的接收和解析 -> 正文阅读

[网络协议]使用HTTP方式发送请求及json数据的接收和解析

目录

需求

请求端

1,添加依赖

2,请求对象

3,请求工具类

4,请求测试(事先开启接收端的服务)

接收端

数据请求模拟


需求

本项目需要通过向对端第三方项目发送一个http的post类型的请求,并且指定了一些请求字段,数据传输采用了json,对请求头没有其他特殊要求,所以这里写了一个demo作为参考

请求端

1,添加依赖

这里我在对json进行发送和解析的时候,我采用了fastjson工具。

        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

2,请求对象

这个对象主要的作用就是将需要发送的参数作为对象的属性然后可以将对象直接转化为json,这种请求在请求参数的类型不一致的时候可以使用(Long,String,DateTIme等等)

public class RequestChange {

    private Long accNum;

    private String servPwdResetChnl;

    private String servPwdResetTime;
 
    private String system;

    //set和get方法  省略.....
}

3,请求工具类

这里多注意代码中这个语句,之前一直没有添加 "UTF-8"这个参数,导致请求的中文参数全是???。如图所示

// 设置请求参数
			StringEntity se = new StringEntity(jsonstr,"UTF-8");
import org.apache.http.*;
import org.apache.http.client.methods.HttpGet;
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.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;

@Component
public class HttpUtil {
	
	/**
	 * httpClient get请求
	 * 
	 * @param url 请求url

	 * @param jsonstr 请求实体 json/xml提交适用
	 * @return 可能为空 需要处理
	 * @throws Exception
	 *
	 */
	public static String sendHttpGet(String url, String jsonstr)
			throws Exception {
		String result = "";
		CloseableHttpClient httpClient = null;
		try {
			httpClient = HttpClients.createDefault();
			
			if(null != jsonstr && !"".equals(jsonstr)) {
				jsonstr = URLEncoder.encode(jsonstr, "UTF-8");
				url = url + "?req=" + jsonstr;
			}
			
			System.out.println("url------------" + url);
			HttpGet httpGet = new HttpGet(url);

			// 设置头信息
			httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
			httpGet.addHeader("Accept", "application/json;charset=utf-8");

			HttpResponse httpResponse = httpClient.execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity resEntity = httpResponse.getEntity();
				result = EntityUtils.toString(resEntity);
			} else {
				readHttpResponse(httpResponse);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			
			if (httpClient != null) {
				httpClient.close();
			}
		}
		return result;
	}

	/**
	 * httpClient post请求
	 * 
	 * @param url 请求url

	 * @param jsonstr 请求实体 json/xml提交适用
	 * @return 可能为空 需要处理
	 * @throws Exception
	 *
	 */
	public static String sendHttpPost(String url, String jsonstr)
			throws Exception {
		String result = "";
		CloseableHttpClient httpClient = null;
		try {
			httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);

			// 设置头信息
			httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
			httpPost.addHeader("Accept", "application/json;charset=utf-8");

			System.out.println("放入到请求体参数为="+jsonstr);

			// 设置请求参数
			StringEntity se = new StringEntity(jsonstr,"UTF-8");
			httpPost.setEntity(se);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity resEntity = httpResponse.getEntity();
				result = EntityUtils.toString(resEntity);
			} else {
				readHttpResponse(httpResponse);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (httpClient != null) {
				httpClient.close();
			}
		}
		return result;
	}
	
	public static String readHttpResponse(HttpResponse httpResponse)
			throws ParseException, IOException {
		StringBuilder builder = new StringBuilder();
		// 获取响应消息实体
		HttpEntity entity = httpResponse.getEntity();
		// 响应状态
		builder.append("status:" + httpResponse.getStatusLine());
		builder.append("headers:");
		HeaderIterator iterator = httpResponse.headerIterator();
		while (iterator.hasNext()) {
			builder.append("\t" + iterator.next());
		}
		// 判断响应实体是否为空
		if (entity != null) {
			String responseString = EntityUtils.toString(entity);
			builder.append("response length:" + responseString.length());
			builder.append("response content:"
					+ responseString.replace("\r\n", ""));
		}
		return builder.toString();
	}

	public static void main(String[] args) throws Exception {
		System.out.println(sendHttpGet("http://127.0.0.1:8080//AccountSynchro", "{\"login\" : \"\", \"alias\" : \"153057123231021\", \"passwd\" : \"122323456\"}"));

	}
}

4,请求测试(事先开启接收端的服务)

主要就是将请求对象进行赋值,然后通过fastJson将对象转化为将json数据然后进行请求,

这里需要注意的是接受请求的时候 ,这里我进行了一个格式话的接受json数据的解析,如果不能

//解析返回的json字符串  返回的数据为="{\"msg\":\"fail\",\"data\":\"没啥数据\"}"  带有转义字符需要进行重新编译

        Object parse = JSON.parse(resultJson);

        String s2 = parse.toString();

        RespChange respChange = JSON.parseObject(s2, RespChange.class);

        System.out.println(respChange.getMsg());

全部请求和解析json代码


@SpringBootTest(classes = UagApplication.class)
public class HttpTest {

    //获取到传送工具类
//    @Autowired
//    private HttpUtil httpUtil;


    //获取到请求路径
    @Value("${Changes.remind.path}")
    private String remindPath="";


    @Autowired
    private ProvincialEvents provincialEvents;


    @Autowired
    private ITransactionIdManager transIdManager = null;



    @Test
    public  void  test1() throws Exception {
        System.out.println("hello world");

        //测试发送 json数据 多个参数不同类型

        long accNum=1111;

        String system="uam";

        //将参数字段转化为字符串 创建一个对象

        RequestChange requestChange = new RequestChange();

        requestChange.setAccNum(accNum);
       //requestChange.setServPwdResetChnl(servPwdResetChnl);
        requestChange.setServPwdResetChnl("好的");
        //创建当前时间


        Date date = Calendar.getInstance().getTime();

        DateFormat dateFormat = new SimpleDateFormat("YYYYMMddHHmmss");

        String format = dateFormat.format(date);

        requestChange.setServPwdResetTime(format);

        requestChange.setSystem(system);

        System.out.println("转化后的时间为="+requestChange.getServPwdResetTime());



        //将对象转化为json

        String s = JSON.toJSONString(requestChange);

        System.out.println("对象转化为json之后的格式="+s);

        if (StringUtil.isEmptyString(remindPath)){
            System.out.println("路径没有获取到"+remindPath);
        }
        System.out.println("路径获取到="+remindPath);

        String resultJson = HttpUtil.sendHttpPost(remindPath, s);

        System.out.println("返回的数据为="+resultJson);


        //解析返回的json字符串  返回的数据为="{\"msg\":\"fail\",\"data\":\"没啥数据\"}"  带有转义字符需要进行重新编译

        Object parse = JSON.parse(resultJson);

        String s2 = parse.toString();

        RespChange respChange = JSON.parseObject(s2, RespChange.class);

        System.out.println(respChange.getMsg());


    }

}

接收端

接收请求发过来的json数据,并且可以解析成自己需要格式(String,Map,对象)

@RestController
@RequestMapping(value ="/test")
public class TestHttpController {

    @RequestMapping(value = "/http",method=RequestMethod.POST)
    public String  testHttp(@RequestBody JSONObject json){
        

        //解析json数据,获取到每一个属性对应的值
        System.out.println(json.getString("accNum"));
        System.out.println(json.getString("servPwdResetChnl"));
        System.out.println(json.getString("servPwdResetTime"));
        System.out.println(json.getString("system"));
        
        
        //返回响应json字符串
        HashMap<String, String> map = new HashMap<>();
        map.put("msg","success");
        map.put("data","没啥数据");
        String s = JSON.toJSONString(map);
        return  s;

    }

}

数据请求模拟

1,开始接收端服务

2,开启请求端服务发送请求

?

?

参考文章:

json如何传输数据?

(31条消息) Java中使用JSON数据传递_杀神lwz的博客-CSDN博客_java传递json格式数据

接受方如何解析

(31条消息) Java接收json参数_詹Sir(开源字节)的博客-CSDN博客_java接收json对象

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-09-30 01:21:54  更:2022-09-30 01:22:27 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年3日历 -2024/3/29 22:38:12-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码