用maven创建基于wink的rest服务(四)-携带xml和gson的post请求

通过<用maven创建基于wink的rest服务(一)(二)(三)>的学习,我们知道了如何构建一个非常简单的
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服务的小例子,希望能帮助到您!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值