java自带的java.net包中包含了网络通信功能,其中URLConnection它代表应用程序和 URL 之间的通信链接,此类的实例可用于读取和写入此 URL 引用的资源。
下面通过Post向服务器传输Json数据,并接收服务器的响应。在处理JSON数据时,使用了Alibaba的fastjson包
这是客户端代码:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import com.alibaba.fastjson.JSONObject; public class PostTest { public static String sendPost(String url , String param) { String result = ""; try { URL realUrl = new URL(url); //构造一个到指定URL的连接 URLConnection conn = realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setDoOutput(true); conn.setDoInput(true); try { JSONObject user = new JSONObject(); user.put("email", "123@163.com"); user.put("password", "123456789"); //将JSON数据添加到输出流中 OutputStream ot = conn.getOutputStream(); ot.write(user.toString().getBytes()); PrintWriter out = new PrintWriter(ot); out.flush(); } catch (Exception e) { } try( //接收服务器端发回的响应 BufferedReader in = new BufferedReader(new InputStreamReader (conn.getInputStream() , "utf-8"))) { String line; while ((line = in.readLine())!= null) { result += "\n" + line; } } } catch(Exception e) { System.out.println("POST异常" + e); e.printStackTrace(); } return result; } public static void main(String args[]) { //使用本地Tomcat服务器,已经将应用a部署到了Tomcat容器中 String s1 = PostTest.sendPost("http://localhost:8080/a/aa" , "name=Tom&pass=123456"); System.out.println(s1); } }
下面是servlet方代码:
import java.io.BufferedReader; import java.io.IOException; import java.io.PrintStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSONObject; public class Jsonget extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuffer jb = new StringBuffer(); String line = null; String result = ""; try { //读取输入流到StringBuffer中 BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } try { //使用JSONObject的parseObject方法解析JSON字符串 JSONObject jsonObject = JSONObject.parseObject(jb.toString()); result = jsonObject.toJSONString(); } catch (Exception e) { // crash and burn throw new IOException("Error parsing JSON request string"); } //先将服务器收到的JSON字符串打印到客户端,再将该字符串转换为JSON对象然后再转换成的JSON字符串打印到客户端 PrintStream out = new PrintStream(response.getOutputStream()); out.println(jb.toString()); out.println(result); } }
下面是启动Tomcat后,执行客户端程序后客户端收到的响应:
可以看到客户端成功收到了服务器的响应,服务器准确收到了客户端发送的JSON数据