HttpPost Josn数据及服务端返回Json数据代码详解

最近在模拟post json数据到服务端,然后返回json信息,当然也要实现模拟服务端的代码,服务单可以用controller实现,但是发现一个问题,就是返回来的是个页面,页面中才包含返回的json数据,怎么取出去来了,网上博客一般写的都是客户端的post,后来猛然想到以前和老师学安卓的时候的有段代码就是把返回的json数据放在页面上,才发现可以用getWriter()把页面中的json数据单独打在页面中

代码实现如下:

模拟的服务端:

	@RequestMapping(value = "/loginTest", method = RequestMethod.POST)
	public void test(HttpServletRequest request,HttpServletResponse response) throws Exception {
		//JSONObject json=JSONObject.fromObject(data);
		 // 读取请求内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }

        // 将资料解码
        String reqBody = sb.toString();
		JSONObject json=JSONObject.fromObject(reqBody);
    	String data = "{'isAdmin':'true', 'usename':wsf}";
        
    	PrintWriter writer = response.getWriter();
    	writer.write(data);    //这里是你要返回的字符串
    	writer.flush();
    	writer.close(); 	
    	}


模拟的发送端:

/**
 * @file TestPost.java
 * @date 2016年9月10日
 * @version 3.4.1
 *
 * Copyright (c) 2013 Sihua Tech, Inc. All Rights Reserved.
 */
package cn.com.dongyaTest.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;


/**
 * 
 *
 * @author chengjian.he
 * @version  3.4, 2016年9月10日 下午3:03:50 
 * @since   Yeexun 3.4
 */
public class TestPost {

	public static int postBody(String urlPath, String data) throws Exception {
		try{  
		            // Configure and open a connection to the site you will send the request  
		            URL url = new URL(urlPath);  
		            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();  
		            // 设置doOutput属性为true表示将使用此urlConnection写入数据  
		            urlConnection.setDoOutput(true);  
		            // 定义待写入数据的内容类型,我们设置为application/x-www-form-urlencoded类型  
		            urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");  
		            // 得到请求的输出流对象  
		            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());  
		            // 把数据写入请求的Body  
		            out.write(data);  
		            out.flush();  
		            out.close(); 
		              
		            // 从服务器读取响应  
		            InputStream inputStream = urlConnection.getInputStream();  
		            String encoding = urlConnection.getContentEncoding();  
		            String body = IOUtils.toString(inputStream, encoding);  
		            if(urlConnection.getResponseCode()==200){
		            return 200;
		            }else{
		            throw new Exception(body);
		            }
		        }catch(IOException e){
		        throw e;
		        }
		}
	
	  
	  public static JSONObject doPost(String url,JSONObject json){
	    DefaultHttpClient client = new DefaultHttpClient();
	    HttpPost post = new HttpPost(url);
	    JSONObject response = null;
	    try {
	      StringEntity s = new StringEntity(json.toString());
	      s.setContentEncoding("UTF-8");
	      s.setContentType("application/json");//发送json数据需要设置contentType
	      post.setEntity(s);
	      HttpResponse res = client.execute(post);
	      if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
	        HttpEntity entity = res.getEntity();
	        String result = EntityUtils.toString(res.getEntity());// 返回json格式:
	        response = JSONObject.fromObject(result);
	      }
	    } catch (Exception e) {
	      throw new RuntimeException(e);
	    }
	    return response;
	  }


		public static void main(String[] args) {
		try {
		//	String data = "{'username':'shihuan', 'password':123456}";
		//TestPost.postBody("http://localhost:8009/wechatyeexun/loginTest.do", data);
			 String url = "http://localhost:8009/wechatyeexun/loginTest.do";
			    JSONObject params = new JSONObject();
			    params.put("username", "wsf");
			    params.put("password", "123");
			    String ret = doPost(url, params).toString();
			    System.out.println(ret);
			   /* final String APPLICATION_JSON = "application/json";
			    
			    final String CONTENT_TYPE_TEXT_JSON = "text/json";
			    DefaultHttpClient httpClient = new DefaultHttpClient();
		        HttpPost httpPost = new HttpPost(url);
		        httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		        
		        StringEntity se = new StringEntity(params.toString());
		        se.setContentType(APPLICATION_JSON);
		        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
		        httpPost.setEntity(se);
		        httpClient.execute(httpPost);*/
		} catch (Exception e) {
		e.printStackTrace();
		}
		}
		
		
}

当然,也可以用火狐的Poster直接测试更方便,下面时候返回来的json数据,希望对你有所帮助




  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值