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();
}
}
}
使用中文消息会乱码!!!