http协议发送header+body+json及接收解析

Posted vmkash

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了http协议发送header+body+json及接收解析相关的知识,希望对你有一定的参考价值。

http发送header+body+json和返回

探究http协议发送header,发送body,发送json

探究htt协议接收header,接收body,解析json

(1)使用jar包

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180130</version>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
        </dependency>

(2)发送端

package com.his.vh.test;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.junit.Test;

/**
 *@file_name:TestHis.java
 *@description:
 *
 *@time:2018年5月21日 上午9:31:43
 *@author:sf
 */
public class TestRegister {
    
    @Test
    public void register() throws Exception{    
        
        //封装发送参数
         Map<String, String> paras = new HashMap<String, String>();
        //——————————————————————————————————————————————————————
         paras.put("url", "http://127.0.0.1:8083/front/register");
         paras.put("username", "username_xiaoming");
         paras.put("password", "password_xiaoming");
         
         String msg_package = "{\"package\": {"
                    +"\"head\": {"
                    +"\"busseID\": \"C210\","
                    +"\"sendTradeNum\": \"20190701083030-10011001-0001\","
                    +"\"senderCode\": \"0000\","
                    +"\"senderName\": \"医院\","
                    +"\"receiverCode\": \"0000\","
                    +"\"receiverName\": \"保险\","
                    +"\"intermediaryCode\": \"0000\","
                    +"\"intermediaryName\": \"ms\","
                    +"\"hosorgNum\": \"001\","
                    +"\"hosorgName\": \"张三\","
                    +"\"systemType\": \"1\","
                    +"\"busenissType\": \"2\","
                    +"\"standardVersionCode\": \"version:1.0.0\","
                    +"\"clientmacAddress \": \"30BB7E0A5E2D \","
                    +"\"recordCount \": \"1\"},"
                    +"\"body\": ["
                    +" {"
                    +"\"medicalNum\": \"001\","
                    +"\"listCat\": \"张三\","
                    +"\"medicalItemCat\": \"1\","
                    +"\"recipeNum\": \"2\""
                    +"}"
                    +"],"
                    +"\"additionInfo\": {"
                    +"\"errorCode\": \"123\","
                    +"\"errorMsg\": \"\","
                    +"\"receiverTradeNum\": \"\","
                    +"\"correlationId\": \"\","
                    +"\"asyncAsk\": \"0\","
                    +"\"callback\": \" http://127.0.0.1:8080/xxxx/xxxx.do\","
                    +"\"curDllAddr\": \"\"}}}";
         
         paras.put("package", msg_package);
         
        //——————————————————————————————————————————————————————
            //创建客户端
            HttpClient client = HttpClients.createDefault();
            //建立连接
            HttpPost post = new HttpPost(paras.get("url"));
            //设置Content-type
            post.addHeader("Content-type", "application/json; charset=utf-8");
            
            //从map中取出参数,放入header中
            post.addHeader("header_1", paras.get("username"));
            post.addHeader("header_2", paras.get("password"));
            post.addHeader("header_3", paras.get("package"));
    
            //设置body的接收类型
            post.setHeader("Accept", "application/json");        
            
          
            JSONObject json = new JSONObject();

            //body中封装数据

            json.put("body_1", paras.get("username"));
            json.put("body_2", paras.get("password"));
            json.put("body_3", paras.get("package"));

            post.setEntity(new StringEntity(json.toString(),"UTF-8"));
            
            //发送post请求
            HttpResponse httpResponse = client.execute(post);
            
            //HttpEntity用于接收【response.getWriter().print(内容)】中print的内容;
            HttpEntity entity = httpResponse.getEntity();
            
            //接收httpResponse的结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //取出状态码
            resultMap.put("status", httpResponse.getStatusLine().toString());
            //取出print的值
            resultMap.put("responseContent", EntityUtils.toString(entity));
//          resultMap.put("responseContent", EntityUtils.toString(entity,"UTF-8"));//解决乱码
           
            //获取所有返回的header
            System.out.println("\r\n==================== print return headers ==================== ");
            Header[] headers = httpResponse.getAllHeaders();
            for (Header header : headers) {
                System.out.println(header);
            }
                    
            //response 中获取 TOKEN
            if (httpResponse.containsHeader("TOKEN")) {
                resultMap.put("TOKEN", httpResponse.getFirstHeader("token").toString());
            }
            
            //打印返回值的map 
            System.out.println("\r\n==================== print return map ==================== ");
           for(String key:resultMap.keySet()){
               System.out.println("==========> "+ key +" : "+ resultMap.get(key));
           }

    }

}

(3)接收端

package com.hisfront.vh.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.configuration.Configuration;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hisfront.vh.utils.AssistUtils;
import com.hisfront.vh.utils.DcsHttpUtils;
import com.hisfront.vh.utils.PropertiesUtils;
import com.jayway.jsonpath.JsonPath;

@Controller
@RequestMapping(value = "/front")
public class FrontController {


    private static Logger logger = LoggerFactory.getLogger(FrontController.class);

    Configuration config = PropertiesUtils.getConfiguration();

    @Autowired
    private ServletContext servletContext;

    @RequestMapping("/callCloud")
    public void callCloud(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("-----------------  打印headers -----------------");
        DcsHttpUtils.printHeaders(request);

        Map<String, String> toCloudMap= new HashMap();


        //从header中取出报文
        //map.put("DATAGRAM",request.getHeader("DATAGRAM"));

        //从servletContext中取出TOKEN
        toCloudMap.put("TOKEN", request.getSession().getServletContext().getAttribute("TOKEN").toString());

        toCloudMap.put("url", config.getString("cloud.url.senddata"));
        toCloudMap.put("user", request.getHeader("user"));
        toCloudMap.put("password", request.getHeader("password"));

        //从body中取出报文
        try {
            String bodyContent = DcsHttpUtils.getPostBodyContent(request);

            // JsonPath.read(bodyContent, "$.package");
            System.out.println("\r\n\r\n"+bodyContent);
            //System.out.println("\r\n\r\n"+ JsonPath.read(bodyContent, "$.package"));

            toCloudMap.put("package", bodyContent);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("============> 获取post内容失败");
        }

        System.out.println("-----------------  打印map参数 -----------------");
        AssistUtils.printMap(toCloudMap);

        System.out.println("----------------  返回响应数据给his  -----------------");
        try {
            response.setHeader("TOKEN", "front_token");
            response.getWriter().println("22222222");
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("返回响应数据");
        }
        System.out.println("----------------  模拟请求cloud  -----------------");
        Map<String, String> resultMap = null;
        try {
            resultMap = DcsHttpUtils.submitPost(toCloudMap);

            System.out.println("==================AssistUtils.printMap(resultMap);===================\r\n\r\n");
            AssistUtils.printMap(resultMap);

            String responseContent = resultMap.get("responseContent");
            System.out.println(responseContent);
            System.out.println("sendTradeNum =======> " + JsonPath.read(responseContent, "$.package.head.sendTradeNum"));
            System.out.println("medicalNum =======> " + JsonPath.read(responseContent, "$.package.body[0].medicalNum"));
            String errorCode = JsonPath.read(responseContent, "$.package.additionInfo.errorCode");
            //errorCode 为 0 正常,说明发送成功
            if ("0" == errorCode) {
                logger.info("---------------- requestCloud and sendData successfully ---------------------");
            } else if ("0001" == errorCode) { //token 过期,重新注册
                logger.info("---------------- token fired , reregister again ---------------------");

                toCloudMap.put("url", config.getString("cloud.url.register"));

                //重新注册
                Map<String, String> registerResultMap = DcsHttpUtils.submitPost(toCloudMap);
                logger.info("---------------- reregister successfully ---------------------");
                logger.info("----------------registerResultMap---------------------");
                AssistUtils.printMap(registerResultMap);
                //TOKEN 放 servletContext
                servletContext.setAttribute("TOKEN", registerResultMap.get("TOKEN"));
                toCloudMap.put("TOKEN", registerResultMap.get("TOKEN"));
                toCloudMap.put("url", config.getString("cloud.url.senddata"));
                Map<String, String> sendDataResultMap = DcsHttpUtils.submitPost(toCloudMap);
                logger.info("---------------- requestCloud and sendData successfully ---------------------");

                System.out.println("errorCode =======> " + errorCode);

                System.out.println("sendTradeNum =======> " + JsonPath.read(responseContent, "$.package.head.sendTradeNum"));
                System.out.println("medicalNum =======> " + JsonPath.read(responseContent, "$.package.body[0].medicalNum"));
                logger.info("---------------sendDataResultMap--------------------");
                AssistUtils.printMap(sendDataResultMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("directCPST 请求 cloud 失败。。。");
        }

        System.out.println(request.getSession().getServletContext().getAttribute("TOKEN"));

    }


    //http://localhost:8081/front/callHis
    /////////////////////////////////////////////////////////////////////////////////////////////////
    @RequestMapping("/callHis")
    public void callHis(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("-----------------  打印headers -----------------");
        DcsHttpUtils.printHeaders(request);

        Map<String, String> mapToHis = new HashMap();

        mapToHis.put("url", config.getString("hosp.url"));
        System.out.println(config.getString("hosp.url"));
        mapToHis.put("user", request.getHeader("user"));
        mapToHis.put("password", request.getHeader("password"));

        System.out.println("-----------------  打印map参数 -----------------");
        AssistUtils.printMap(mapToHis);

        System.out.println("----------------  模拟请求 his  -----------------");
        try {
           // response.setCharacterEncoding("UTF-8");
            Map<String, String> mapFromHis = DcsHttpUtils.submitPost(mapToHis);

            System.out.println("----------------   AssistUtils.printMap(mapFromHis);  -----------------");
            AssistUtils.printMap(mapFromHis);

            System.out.println("----------------   AssistUtils.printMap(mapToCloud);  -----------------");
            Map<String ,String > mapToCloud = new HashMap<>();
            mapToCloud.put("package",mapFromHis.get("responseContent"));
            mapToCloud.put("url",config.getString("cloud.url.senddata"));
            AssistUtils.printMap(mapToCloud);
            System.out.println("----------------  结果返给 cloud  -----------------");
            try {
                response.setCharacterEncoding("UTF-8");
                response.getWriter().print(mapFromHis.get("responseContent"));
              //  DcsHttpUtils.submitPost(mapToCloud);
                System.out.println("--------------  结果返给 cloud successfully -------------------------");
            } catch (Exception e) {
                logger.info(" fastCPST 请求 cloud 失败。。。");
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("fastCPST 请求 his 。。。");
        }
    }

    @RequestMapping(value="/register")
    public void register(HttpServletRequest request, HttpServletResponse response) throws Exception{
        
        System.out.println("\r\n==================== print request header ==================== ");
        //打印header 可封装成方法
         Enumeration headerNames = request.getHeaderNames();
         while (headerNames.hasMoreElements()) {
             String key = (String) headerNames.nextElement();
             String value = request.getHeader(key);
             System.out.println("===> " + key + " --- " + value);
         }
        
         //获取body
         try {
             
            // 获取bodyContent,可封装成方法----start
            request.setCharacterEncoding("UTF-8");
    
             StringBuffer sb = new StringBuffer();
             BufferedReader read = request.getReader();
             String str;
             while ((str = read.readLine()) != null) {
                 sb.append(str + "\n");
             }
             read.close();
             String bodyContent =sb.toString();
             System.out.println("\r\n==================== print request body ==================== ");
             System.out.println(bodyContent);
          // 获取bodyContent,可封装成方法----end
          
        System.out.println("\r\n==================== print request body ==================== ");
         //从bodyContent中获取json串的参数
         JSONObject jo = new JSONObject(bodyContent);
         System.out.println("body_1 ============> "+ jo.get("body_1"));
         System.out.println("body_2 ============> "+ jo.get("body_2"));
         System.out.println("body_3 ============> "+ jo.get("body_3"));
            
         
         //使用JsonPath,获取json的value         
         System.out.println("\r\n==================== print request body package==================== ");
         String responseContent = (String) jo.get("body_3");
   
         System.out.println("sendTradeNum =======> " + JsonPath.read(responseContent, "$.package.head.sendTradeNum"));
         System.out.println("medicalNum =======> " + JsonPath.read(responseContent, "$.package.body[0].medicalNum"));
         System.out.println("errorCode =======> " +JsonPath.read(responseContent, "$.package.additionInfo.errorCode"));
        
         } catch (Exception e) {
            e.printStackTrace();
        }

         //获取header中的值
        String username = request.getHeader("header_1");
        String password = request.getHeader("header_2");
        
        
        //加密产生token
        //String token = Base64Encrypt.Encode(username+password);//使用相应的加密方法生成token
        String token = username+"_"+password;//这里直接用 username_password 作为token
        
        //把token放入session
        request.getSession().setAttribute("token", token);
        
        //设置response的header
        response.setHeader("token", "return_token --> "+token);
        response.setHeader("header_1", "return_token --> header_1 ");
        response.setHeader("header_2", "return_token --> header_2");
        
        response.setCharacterEncoding("UTF-8");
        try {
            //把token写到 StringEntity 中,返回给请求对象
            response.getWriter().print(token);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
    }


}

(4)发送端console

==================== print return headers ==================== 
Set-Cookie: JSESSIONID=22340FC21A26A7E2B062AB718309E716; Path=/; HttpOnly
token: return_token --> username_xiaoming_password_xiaoming
header_1: return_token --> header_1 
header_2: return_token --> header_2
Content-Length: 35
Date: Mon, 21 May 2018 09:45:17 GMT

==================== print return map ==================== 
==========> TOKEN : token: return_token --> username_xiaoming_password_xiaoming
==========> responseContent : username_xiaoming_password_xiaoming
==========> status : HTTP/1.1 200 

(5)接收端console

==================== print request header ==================== 
===> content-type --- application/json; charset=utf-8
===> header_1 --- username_xiaoming
===> header_2 --- password_xiaoming
===> header_3 --- {"package": {"head": {"busseID": "C210","sendTradeNum": "20190701083030-10011001-0001","senderCode": "0000","senderName": ";b","receiverCode": "0000","receiverName": "Yi","intermediaryCode": "0000","intermediaryName": "ms","hosorgNum": "001","hosorgName": "     ","systemType": "1","busenissType": "2","standardVersionCode": "version:1.0.0","clientmacAddress ": "30BB7E0A5E2D ","recordCount ": "1"},"body": [ {"medicalNum": "001","listCat": "    ","medicalItemCat": "1","recipeNum": "2"}],"additionInfo": {"errorCode": "123","errorMsg": "","receiverTradeNum": "","correlationId": "","asyncAsk": "0","callback": " http://127.0.0.1:8080/xxxx/xxxx.do","curDllAddr": ""}}}
===> accept --- application/json
===> content-length --- 866
===> host --- 127.0.0.1:8083
===> connection --- Keep-Alive
===> user-agent --- Apache-HttpClient/4.5.5 (Java/1.8.0_131)
===> accept-encoding --- gzip,deflate

==================== print request body ==================== 
{"body_3":"{\"package\": {\"head\": {\"busseID\": \"C210\",\"sendTradeNum\": \"20190701083030-10011001-0001\",\"senderCode\": \"0000\",\"senderName\": \"医院\",\"receiverCode\": \"0000\",\"receiverName\": \"保险\",\"intermediaryCode\": \"0000\",\"intermediaryName\": \"ms\",\"hosorgNum\": \"001\",\"hosorgName\": \"张三\",\"systemType\": \"1\",\"busenissType\": \"2\",\"standardVersionCode\": \"version:1.0.0\",\"clientmacAddress \": \"30BB7E0A5E2D \",\"recordCount \": \"1\"},\"body\": [ {\"medicalNum\": \"001\",\"listCat\": \"张三\",\"medicalItemCat\": \"1\",\"recipeNum\": \"2\"}],\"additionInfo\": {\"errorCode\": \"123\",\"errorMsg\": \"\",\"receiverTradeNum\": \"\",\"correlationId\": \"\",\"asyncAsk\": \"0\",\"callback\": \" http:\/\/127.0.0.1:8080\/xxxx\/xxxx.do\",\"curDllAddr\": \"\"}}}","body_1":"username_xiaoming","body_2":"password_xiaoming"}


==================== print request body ==================== 
body_1 ============> username_xiaoming
body_2 ============> password_xiaoming
body_3 ============> {"package": {"head": {"busseID": "C210","sendTradeNum": "20190701083030-10011001-0001","senderCode": "0000","senderName": "医院","receiverCode": "0000","receiverName": "保险","intermediaryCode": "0000","intermediaryName": "ms","hosorgNum": "001","hosorgName": "张三","systemType": "1","busenissType": "2","standardVersionCode": "version:1.0.0","clientmacAddress ": "30BB7E0A5E2D ","recordCount ": "1"},"body": [ {"medicalNum": "001","listCat": "张三","medicalItemCat": "1","recipeNum": "2"}],"additionInfo": {"errorCode": "123","errorMsg": "","receiverTradeNum": "","correlationId": "","asyncAsk": "0","callback": " http://127.0.0.1:8080/xxxx/xxxx.do","curDllAddr": ""}}}

==================== print request body package==================== 
sendTradeNum =======> 20190701083030-10011001-0001
medicalNum =======> 001
errorCode =======> 123

以上是关于http协议发送header+body+json及接收解析的主要内容,如果未能解决你的问题,请参考以下文章

请简要描述客户端发送的http request header都包含哪些内容

postman怎么发送json参数

简述http协议及抓包分析

HTTP 协议详解

HTTP的请求和响应

RN发送http请求例子