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