客户端POST发送json数据给服务端
//请求的地址
String url = "http://localhost:8080/springmvc/request/postRequest";
//创建Http Request(内部使用HttpURLConnection)
ClientHttpRequest request =
new SimpleClientHttpRequestFactory().
createRequest(new URI(url), HttpMethod.POST);
//设置请求头的内容类型头和内容编码(GBK)
request.getHeaders().set("Content-Type", "application/json;charset=gbk");
//以GBK编码写出请求内容体
String jsonData = "{\"username\":\"admin\", \"password\":\"admin\"}";
request.getBody().write(jsonData.getBytes("gbk"));
//发送请求并得到响应
ClientHttpResponse response = request.execute();
System.out.println(response.getStatusCode());
客户端接收服务器端json数据响应
public static void jsonRequest() throws IOException, URISyntaxException {
//请求的地址
String url = "http://localhost:8080/springmvc/response/reponseContent";
//创建Http Request(内部使用HttpURLConnection)
ClientHttpRequest request =
new SimpleClientHttpRequestFactory().
createRequest(new URI(url), HttpMethod.POST);
//设置客户端可接受的媒体类型
request.getHeaders().set("Accept", "application/json");
//发送请求并得到响应
ClientHttpResponse response = request.execute();
//得到响应体的编码方式
Charset charset = response.getHeaders().getContentType().getCharSet();
//得到响应体的内容
InputStream is = response.getBody();
byte bytes[] = new byte[(int)response.getHeaders().getContentLength()];
is.read(bytes);
String jsonData = new String(bytes, charset);
System.out.println("charset : " + charset + ", json data : " + jsonData);
}