最近在模拟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();
- }
- }
- }