使用Apache http client发送json数据(demo)

POM依赖 :

        <dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.12</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.46</version>
		</dependency>

客户端代码:

package xyz.jangle.httpclient.test;
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.util.EntityUtils;
//import org.json.JSONObject;

import com.alibaba.fastjson.JSONObject;
 
public class HttpClientSendJson {
    public static void main(String[] args) {
        try {
            // 创建HttpClient实例
            CloseableHttpClient httpClient = HttpClients.createDefault();
 
            // 创建HttpPost实例
            HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/hello/test3");
 
            // 创建JSON数据
            JSONObject json = new JSONObject();
//            json.put("key1", "value1");
//            json.put("key2", "value2");
            json.put("shebeiId", "123");
            json.put("xiaoxiId", "456");
            json.put("xiaoxiType", "1");
 
            // 将JSON数据设置到StringEntity中
            StringEntity entity = new StringEntity(json.toString());
 
            // 设置内容类型
            entity.setContentType("application/json");
 
            // 设置HttpPost实例的实体
            httpPost.setEntity(entity);
 
            // 发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
 
            // 获取响应内容
            String result = EntityUtils.toString(response.getEntity());
 
            // 输出结果
            System.out.println(result);
 
            // 关闭response
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

服务端接收方式:

    @RequestMapping(value = "/test3", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> test3(@RequestBody String test){
		Map<String,Object> map = new HashMap<String,Object>();
		//string
		logger.info("test:"+test);
		try {
			JSONObject jsonObject = JSONObject.parseObject(test);
			String shebeiId = jsonObject.getString("shebeiId");
			String xiaoxiId = jsonObject.getString("xiaoxiId");
			String xiaoxiType = jsonObject.getString("xiaoxiType");
            return xxx(shebeiId, xiaoxiId, map);
		} catch (Exception e) {
			map.put("code", 102);
			map.put("msg", e.toString());
			logger.error("异常:", e);
			return map;
		}
		
	}

参考文献:

1.百度AI

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值