java客戶端與服務器Servlet Json數據傳輸


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數據 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM