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);
// 创建参数队列
List<Student> slist = 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()+"-------------");
}
}
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
</bean>
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>