通过<用maven创建基于wink的rest服务(一)(二)(三)>的学习,我们知道了如何构建一个非常简单的
rest服务器和客户端,并可以通过get和post发送简单的消息,但是在实际业务中,一般传送约定好的文件格式,
例如xml文件格式和json格式.
传xml格式的文件还是json格式的文件,文件格式都可以定义为text/plain,程序可以正常运行,那么这么区分又有什么意义呢?
rest服务器和客户端,并可以通过get和post发送简单的消息,但是在实际业务中,一般传送约定好的文件格式,
例如xml文件格式和json格式.
1.创建客户端,直接看代码.
package com.ilucky.rest.client;
import java.util.HashMap;
import org.apache.wink.client.Resource;
import org.apache.wink.client.RestClient;
import com.google.gson.Gson;
/**
* @author IluckySi
* @date 20140328
*/
public class RestClientService {
public static void main(String[] args) {
try {
RestClient restClient = new RestClient();
Resource resource = restClient.resource("http://192.168.72.153:8080/rest-server/rest/register");
//传送xml文件格式的字符串.
String xml =
"<root>" +
"<head>" +
"<username>username</username>" +
"<password>password</password>" +
"</head>" +
"</root>";
String xmResponse = resource.contentType("application/xml;charset=UTF-8").accept("application/xml;charset=UTF-8").post(String.class, xml);
System.out.println("客户端收到服务器返回的信息: " + xmResponse);
//传送Gson格式的字符串.
Gson gson = new Gson();
HashMap<String, String> map = new HashMap<String, String>();
map.put("username", "username");
map.put("password", "password");
String json = gson.toJson(map);
String jsonResponse = resource.contentType("application/json;charset=UTF-8").accept("application/aaa;charset=UTF-8").post(String.class, json);
System.out.println("客户端收到服务器返回的信息: " + jsonResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.创建服务器,注意如果写@Produces("*;charset=UTF-8")和@Consumes("*;charset=UTF-8"),
意思是说服务器端可以接受任何形式的文件.
package com.iluck.rest.server;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* @author IluckySi
* @date 20140328
*/
@Path("/register")
public interface RestServerService {
@POST
@Produces("*;charset=UTF-8")
@Consumes("*;charset=UTF-8")
public String register(String userInfo);
}
通过前面几个小例子,对基于wink的rest服务有了点了解,同时也存在很多问题,例如本例的客户端中我们无论是
传xml格式的文件还是json格式的文件,文件格式都可以定义为text/plain,程序可以正常运行,那么这么区分又有什么意义呢?
请继续关注以后的博客.
总结:如上是用maven创建的一个基于wink的rest服务的小例子,希望能帮助到您!