客户端代码
public class User {
public static void main(String[] args) throws Exception {
URL url=new URL("http://localhost:8080/web//Post_demo");
String js=
" {\r\n" +
" \"name\": \"zhangsan\",\r\n" +
" \"age\": \"10\",\r\n" +
" \"phone\": \"11111\",\r\n" +
" \"email\": \"11111@11.com\"\r\n" +
" }";
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",js.length()+"");
conn.setDoOutput(true);
conn.getOutputStream().write(js.getBytes());
}
}
服务端
@WebServlet("/Post_demo")
public class Post_demo extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StringBuffer jb=new StringBuffer();
String js;
BufferedReader bf=req.getReader();
while((js=bf.readLine())!=null) {
jb.append(js);
}
JsonObject jsonObject = (JsonObject) new JsonParser().parse(jb.toString());
System.out.println("name:" + jsonObject.get("name").getAsString());
System.out.println("age:" + jsonObject.get("age").getAsInt());
System.out.println("phone:" + jsonObject.get("phone").getAsString());
System.out.println("email:" + jsonObject.get("email").getAsString());
}
}
启动后两边都没有报错也没有反应,到底是哪儿出错了