json的封装以及json的解析
Map<String,Object> jsonMap = new HashMap<>();
jsonMap.put("username","zhangsan");
jsonMap.put("pwd","123");
String contentString = JSONObject.toJSONString(jsonMap);
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 = new URL(urls);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
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<String,Object> jsonMap = new HashMap<>();
jsonMap.put("username","zhangsan");
jsonMap.put("pwd","123");
String contentString = JSONObject.toJSONString(jsonMap);
System.out.println(contentString);
JSONObject jsonObject = JSONObject.parseObject(contentString);
String requestBody = HttpClientJson.post(jsonObject,url);
System.out.println("返回内容"+requestBody);
JSONObject requestJSON = JSONObject.parseObject(requestBody);
|