jersey中常见的请求有GET,POST,PUT,DELETE请求,常见的请求一般是GET,POST.
GET请求的格式一般是:www.xxxx.com?name=aaa&age=111
POT请求格式一般是:www.xxxx.com 消息随着消息体的方式发送给服务端
项目路径:private String serverUri = "http://localhost:8080/restful";
GET请求测试:
get无参数情况:
- @Path("say")
- @GET
- @Produces(MediaType.TEXT_PLAIN)
- public String say() {
- System.out.println("hello world");
- return "hello world";
- }
测试代码:
- @Test
- public void test() {
-
- Client client = ClientBuilder.newClient();
- WebTarget target = client.target(serverUri + "/hello/say");
- Response response = target.request()
- .buildGet()
- .invoke();
- String readEntity = response.readEntity(String.class);
- System.out.println(readEntity);
- response.close();
-
- }
get有参数情况:
- @Test
- public void test() {
-
- Client client = ClientBuilder.newClient();
- WebTarget target = client.target(serverUri + "/hello/say?name=xxx&age=11");
- Response response = target.request()
- .buildGet()
- .invoke();
- String readEntity = response.readEntity(String.class);
- System.out.println(readEntity);
- response.close();
-
- }
测试:
- @Test
- public void test() {
-
- Client client = ClientBuilder.newClient();
- WebTarget target = client.target(serverUri + "/hello/say?name=xxx&age=11");
- Response response = target.request()
- .buildGet()
- .invoke();
- String readEntity = response.readEntity(String.class);
- System.out.println(readEntity);
- response.close();
-
- }
POST请求测试:
- @Path("acceptbean")
- @POST
- @Produces(MediaType.APPLICATION_JSON)
- public String acceptbean(String userBean) {
- return userBean;
- }
测试:
- @Test
- public void postTest() {
-
- Client client = ClientBuilder.newClient();
- WebTarget target = client.target(serverUri + "/hello/acceptbean");
-
- UserBean userBean = new UserBean();
- userBean.setId(111);
- userBean.setUsername("aaaaa");
- Entity<UserBean> entity = Entity.entity(userBean, MediaType.APPLICATION_JSON);
- Response response = target.request()
- .buildPost(entity)
- .invoke();
-
- UserBean readEntity = response.readEntity(UserBean.class);
- System.out.println(StringUtils.getToString(readEntity));
- response.close();
-
- }
说明response.readEntity这个方法:
- public abstract <T> T readEntity(Class<T> entityType);
若返回的数据类型是String类型,则entityType值为String.class
若返回的数据类型是bean类型,则entityType值为Bean.class