json的封装以及json的解析
//Map 转 json
Map jsonMap = new HashMap<>();
jsonMap.put("username","zhangsan");
jsonMap.put("pwd","123");
String contentString = JSONObject.toJSONString(jsonMap);
//System.out.println(contentString); // {"pwd":"123","username":"zhangsan"}
//解析json Map字符串转为json
JSonObject jsonObject = JSONObject.parseObject(contentString);
String username = jsonObject.getString("username");
String pwd = jsonObject.getString("pwd");
System.out.println(username);
System.out.println(pwd);
客户端发送POST请求
工具类
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpClientJson {
public static String post(JSonObject jsonObject, String urls, String encode){
StringBuffer stringBuffer = new StringBuffer();
try{
//建立URL资源
URL url = new URL(urls);
//建立HTTP连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置允许输入
conn.setDoInput(true);
//设置允许输出
conn.setDoOutput(true);
//设置不用缓存 conn.setUseCaches(false);
//设置传递方式
conn.setRequestMethod("POST");
//设置维持长连接
conn.setRequestProperty("Connection","Keep-Alive");
//设置文件字符集
conn.setRequestProperty("Charset","utf-8");
//将发送参数转换为字节数组
byte[] data = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
//设置文件类型
conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
//设置连接超时
conn.setConnectTimeout(10000);
conn.setReadTimeout(60*1000*2);
//开始连接请求
conn.connect();
OutputStream out = new DataOutputStream(conn.getOutputStream());
//写入请求的字符串
out.write(data);
out.flush();
out.close();
//请求返回的状态
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){
System.out.println("连接成功");
//请求返回的数据
InputStream in = conn.getInputStream();
try{
String readline = new String();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(in,"utf-8"));
while ((readline=responseReader.readLine())!=null){
stringBuffer.append(readline);
}
responseReader.close();
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}else {
System.out.println("error="+conn.getResponseCode());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
测试
String url = "";
//定义Map
Map jsonMap = new HashMap<>();
jsonMap.put("username","zhangsan");
jsonMap.put("pwd","123");
//把map转换为字符串
String contentString = JSONObject.toJSONString(jsonMap);
System.out.println(contentString);
//Map字符串转为jsonObject
JSonObject jsonObject = JSONObject.parseObject(contentString);
//发送POST请求
String requestBody = HttpClientJson.post(jsonObject,url);
System.out.println("返回内容"+requestBody);
//解析返回体
JSonObject requestJSON = JSONObject.parseObject(requestBody);