Java通过JSON传递数据访问服务器

  1. Client
    // the server URL
    private String url = "http://server_addr/project_name";
    
    public List<Object> commumicateWithServerByJSON(String para1, String para2)
    {
    	List<Object> resultList = new ArrayList<Object>();
    	Object result = new Object();
    
    	HttpClient httpClient = new DefaultHttpClient();
    	try
    	{
    		// create a JSON object for parameter, set encoding
    		org.json.simple.JSONObject obj = new org.json.simple.JSONObject();
    		obj.put("para1", URLEncoder.encode(para1, HTTP.UTF_8));
    		obj.put("para2", URLEncoder.encode(para2, HTTP.UTF_8));
    		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    		nameValuePairs.add(new BasicNameValuePair("jsonPara", obj.toJSONString()));
    
    		// post request with parameter
    		HttpPost post = new HttpPost(url + "/method.do");
    		post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    		HttpResponse httpClientResponse = httpClient.execute(post);
    
    		// receive the result
    		int status = httpClientResponse.getStatusLine().getStatusCode();
    		String responseStr = null;
    		if(status == HttpStatus.SC_OK)
    		{
    			responseStr = EntityUtils.toString(httpClientResponse.getEntity());
    			
    			// ------------------  result 1 : result is a JSON list  -----------------------
    			// get the result list
    			JSONArray jsonArray = JSONArray.fromObject(responseStr);
    			for(int i = 0; i < jsonArray.size(); i++)
    			{
    				// translate JSON object to bean
    				net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject) jsonArray.get(i);
    				net.sf.json.JSONObject objectJson = jsonObject.getJSONObject("object");
    				Object object = (Object) net.sf.json.JSONObject.toBean(objectJson, Object.class);
    				
    				// add object to list
    				resultList.add(object);
    			}
    			return resultList;
    			
    			// ------------------  result 2 : result is a JSON object  -----------------------
    			net.sf.json.JSONObject objectJson = net.sf.json.JSONObject.fromObject(responseStr);
    			result = (Object) net.sf.json.JSONObject.toBean(objectJson, Object.class);
    			return result;
    		}
    		else
    		{
    			System.out.println("Abnormal returned HTTP Status: " + status);
    		}
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    }

  2. Server
    public void action(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
    	if("POST".equals(request.getMethod()))
    	{
    		// set the encoding
    		request.setCharacterEncoding("UTF-8");
    
    		// get the parameters
    		String jsonPara = request.getParameter("jsonPara");
    		JSONObject jsonObjectPara = JSONObject.fromObject(jsonPara);
    		String para1 = jsonObjectPara.getString("para1");
    		String para2 = jsonObjectPara.getString("para2");
    
    		// result list, filled with objects
    		List<Object> resultList;
    		// result object
    		Object result;
    		// JSON Array String of result list
    		JSONArray resultArrayStr;
    		// JSON Array String of result list
    		String resultObjectStr;
    
    		// result 1 : result is a list
    		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
    		Map<String, Object> map = null;
    		for(Object object : resultList)
    		{
    			map = new HashMap<String, Object>();
    			map.put("object", object);
    			mapList.add(map);
    		}
    		resultArrayStr = JSONArray.fromObject(mapList);
    
    		// result 2 : result is a object
    		JSONObject jsonObject = JSONObject.fromObject(result);
    		resultObjectStr = jsonObject.toString();
    
    		// return the result to client
    		response.setHeader("Cache-Control", "no-cache");
    		response.setContentType("text/json;charset=UTF-8");
    		// return a result list
    		response.getWriter().print(resultArrayStr);
    		// return a result object
    		response.getWriter().print(resultObjectStr);
    	}
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值