java main spring,通过JAVA的main方法直接访问spring mvc 的controller

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.DefaultHttpClient;

import net.sf.json.JSONArray;

public class HttpTest {

public static void addLog() throws IOException {

String url = "http://127.0.0.1:8080/server/httptest";//路径一定要对否则通不过

// 创建默认的httpClient实例.

HttpClient client = new DefaultHttpClient();

// 创建httppost通过post方式访问

HttpPost httppost = new HttpPost(url);

// 创建参数队列

Listslist = new ArrayList<>();

Student student = new Student();

student.setId("1");

student.setName("名称ss");

slist.add(student);

//将数组对象转换为json数组

JSONArray jsonArray = JSONArray.fromObject(slist);

System.out.println(jsonArray.toString());

//作为参数发送到controller

StringEntity entity = new StringEntity(jsonArray.toString(),"utf-8");

entity.setContentEncoding("UTF-8");

entity.setContentType("application/json");

httppost.setEntity(entity);

HttpResponse response = client.execute(httppost);

}

public static void main(String args[]) throws ClientProtocolException, IOException{

HttpTest.addLog();

}

}

//Student.java代码

public class Student {

String name;

String id;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

}

//controller代码

@Controller

public class HttpTestController {

@RequestMapping(value = "/httptest", method = RequestMethod.POST)

@ResponseBody

//将Student接收过来,此时过来的是Json数组,里面对应的属性要和Student里面的保持一致,Spring可以将JSON数组自动转换为对象数组

//但是需要在Spring里面配置才能转,否则不识别

//如何配置在下面有介绍

public void httptest(@RequestBody Student[] data) {

System.out.println(data[0].getId()+"-------------");

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值