HTTP收发消息

S端

  • springboot
  • json
  • 注解
@RestController 
@RequestMapping(value = "test") //请求地址
public class Test {
    
    @PostMapping("test") //请求的方式和地址
    public String doTest(@RequestBody  String param) { //收到消息的参数
    
        JSONObject jsonObject = JSONObject.parseObject(param);
        if (jsonObject.containsKey("test")) {
            String req = jsonObject.getString("test");
            System.out.println("收到消息:" + req);
            jsonObject = new JSONObject();
            jsonObject.put("result", "我收到消息了,我请客你买单!");
        }
        return jsonObject.toString(); //返回的消息
    }
}

C端

  • HttpClient
  • json
public class Time {
    public static void main(String[] args) {
        // 创建httpClient对象
        HttpClient httpClient = HttpClients.createDefault();
        // 请求的地址
        String url = "http://localhost:18082/test/test";
        // 使用post请求方式  get/put等
        HttpPost httpPost = new HttpPost(url);
        // 构造要发送的消息
        JSONObject jsonObject = new JSONObject();
        System.out.println("发送消息:今天晚上你请吃饭");
        jsonObject.put("test", "U pay tonight");
        String json = jsonObject.toString();
        StringEntity se = null;
        try {
            // 将消息放入要发送的实体
            se = new StringEntity(json);
            se.setContentEncoding("UTF-8"); //设置编码方式
            se.setContentType("application/json"); //发送json需要设置contentType
            httpPost.setEntity(se);

            CloseableHttpResponse response =         ((CloseableHttpClient)httpClient).execute(httpPost); // 返回的消息容器

            //解析返结果
            HttpEntity entity = response.getEntity();
            String resStr = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObj1 = JSONObject.fromObject(resStr);

            if (jsonObj1.has("result")) {
                System.out.println("收到回答:" + jsonObj1.get("result").toString());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用中文消息会乱码!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值