resteasy 参数简单解析

来源:互联网 发布:决战刹马镇 知乎 编辑:程序博客网 时间:2024/05/16 05:34

概述      

        resteay对参数解析

get

@PathParam 匹配url变量的,假如@path("/{param}/a"),url访问/adc/a,则@PathParam("param")获取的就adc.

@QueryParam("name"),url访问name=张三&id=1,则@QueryParam("name")的值就是"张三"

post

     测试方式可采用postman的方式

  • application/x-www-form-urlencoded  一般表单的默认提交方式,提交数据将会按照key1=value1&key2=value2的形式进行ur编码
  • multipart/form-data 一般上传文件用到,其生成的数据会已分割线分割不同的字段,正文包含正文以及正文的描述,诸如content-disposition,filename的描述信息,文本或者二进制的正文
  • application/json  这数据已json的格式传递,ajax经常用到,将一个form表单序列化后提交,这种格式有json数据天然的优势,可以传递层级较多的信息
  • text/xml 这个就用到比较少,xml格式文件远不如json来的方便,更适用于xml-rpc协议这种http中用xml进行数据交换的场景
  • ....


       制定消费类型 ;@Consumes   默认*/*

application/x-www-form-urlencoded  

     @FormParam("name"),MultivaluedMap<String,String> params

multipart/form-data

  • 对简单的文本或者pojo的value的形式,可直接用map--('中文乱码,看下)
  • 文件上传,可使用MultipartFormDataInput

raw

        对应的content_type有多种
  • txt为content_type=text/plain,原生的数据,直接用一个string 参数接受就可以
  • json对应content_type=application/json,也可以直接用string接受
  • js对应content_type=application/json
  • ....

binary

        用byte[]接收
       解决multipart/form-data参数中文乱码问题 定义一个ReaderInterceptor( 或者ContainerResponseFilter),以ReaderInterceptor为例
public class ReadCharsetInterceptor implements ReaderInterceptor {@Overridepublic Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {context.setProperty(InputPart.DEFAULT_CHARSET_PROPERTY,"UTF-8");//resteasy.provider.multipart.inputpart.defaultCharset//context.setProperty(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY,"UTF-8");//resteasy.provider.multipart.inputpart.defaultContentTypereturn context.proceed();}}

使用pojo接收参数

一般参数

testgetvo
import javax.ws.rs.QueryParam;public class TestGetVo {@QueryParam("name")private String name;@QueryParam("age")private Integer agae;@QueryParam("marriage")private Boolean marriage;@QueryParam("time")private DateParam time;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAgae() {return agae;}public void setAgae(Integer agae) {this.agae = agae;}public Boolean getMarriage() {return marriage;}public void setMarriage(Boolean marriage) {this.marriage = marriage;}public DateParam getTime() {return time;}public void setTime(DateParam time) {this.time = time;}}
testpostvo
import javax.ws.rs.FormParam;public class TestPostVo {@FormParam("name")private String name;@FormParam("age")private Integer agae;@FormParam("marriage")private Boolean marriage;@FormParam("time")private DateParam time;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAgae() {return agae;}public void setAgae(Integer agae) {this.agae = agae;}public Boolean getMarriage() {return marriage;}public void setMarriage(Boolean marriage) {this.marriage = marriage;}public DateParam getTime() {return time;}public void setTime(DateParam time) {this.time = time;}}

date

date封装(date不能直接接收)
public class DateParam {  private final Date date;  public DateParam(String time){    if (time == null) {      this.date = null;      return;    }    //根据传递的参数格式不同进行不同 的转变    this.date = new Date(Long.parseLong(time));  }  public Date getDate() {    return date;  }}

test

postman等工具类

import javax.ws.rs.BeanParam;import javax.ws.rs.Consumes;import javax.ws.rs.FormParam;import javax.ws.rs.GET;import javax.ws.rs.POST;import javax.ws.rs.Path;import javax.ws.rs.QueryParam;import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Response;import org.jboss.resteasy.annotations.Form;import org.springframework.stereotype.Component;@Path("/test")@Componentpublic class TestResource {/**********************接收参数解析test * 测试参数String Integer Date Boolean * 测试方式:post(x-www-form-urlencoded) || get *  * 注:解析参数接收都是以string的形式接收,对象的valueOf 或者构造器(参数必须为String)进行转换。所以long ,integer ,string,boolean可直接转 * 但date需定义一个包装类 * ***********************//*****************post***********************///@Form@POST@Path("/pojo")@Consumes(MediaType.APPLICATION_FORM_URLENCODED)public Response testPostPojo(@Form TestPostVo vo)  {System.out.println("name:"+ vo.getName());System.out.println("age:"+ vo.getAgae());System.out.println("marriage:"+ vo.getMarriage());System.out.println("time:" + (vo.getTime()==null?"null":vo.getTime().getDate()));return Response.status(200).entity("操作成功").build();  }//@FormParam@POST@Path("/param")@Consumes(MediaType.APPLICATION_FORM_URLENCODED)public Response testPostParam(@FormParam("name") String name, @FormParam("age") Integer age,@FormParam("time") DateParam time, @FormParam("marriage") Boolean marriage) throws Exception {System.out.println("name:"+ name);System.out.println("age:"+age);System.out.println("marriage:"+marriage);System.out.println("time:" + (time == null ? "null" : time.getDate()));return Response.status(200).entity("操作成功").build();  }/*****************get***********************///@QueryParam@GET@Path("/param")public Response testGetParam(@QueryParam("name") String name, @QueryParam("age") Integer age,@QueryParam("time") DateParam time, @QueryParam("marriage") Boolean marriage) throws Exception {System.out.println("name:"+ name);System.out.println("age:"+age);System.out.println("marriage:"+marriage);System.out.println("time:" + (time == null ? "null" : time.getDate()));return Response.status(200).entity("操作成功").build();  }//@BeanParam@GET@Path("/pojo")public Response testGetPojo(@BeanParam TestGetVo vo) throws Exception {System.out.println("name:"+ vo.getName());System.out.println("age:"+ vo.getAgae());System.out.println("marriage:"+ vo.getMarriage());System.out.println("time:" + (vo.getTime()==null?"null":vo.getTime().getDate()));return Response.status(200).entity("操作成功").build();  }/**********************接收参数解析test***********************/}

httpclient等java客户端

import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.NameValuePair;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;public class TestParam {private static RequestConfig requestConfig;static {// 基础配置requestConfig = RequestConfig.custom()// 从连接池中获取连接的超时时间(ms).setConnectionRequestTimeout(3000)// 与服务器连接超时时间:httpclient会创建一个异步线程用以创建socket连接,此处设置该socket的连接超时时间(ms).setConnectTimeout(3000)// socket读数据超时时间:从服务器获取响应数据的超时时间(ms).setSocketTimeout(3000).build();}public static void main(String[] args) {CloseableHttpClient httpClient =  null;httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();CloseableHttpResponse response = null;//String url = "http://localhost:8083/myapp/api/param";String url = "http://localhost:8083/myapp/api/pojo";/*******************post***********************/HttpPost httpPost = new HttpPost(url);try {//httpPost.setEntity(new StringEntity(getStringEntity(), "utf-8"));httpPost.setEntity(new UrlEncodedFormEntity(getPostparams(), "utf8"));response = httpClient.execute(httpPost);HttpEntity httpEntity = response.getEntity();if (httpEntity != null) {String result = EntityUtils.toString(httpEntity);System.out.println(result);// 确保HTTP响应内容全部被读出或者内容流被关闭EntityUtils.consume(httpEntity);}} catch (Exception e) {e.printStackTrace();} finally {httpPost.releaseConnection();try {if (response != null) {response.close();;}/*if (httpClient != null) {//此处注释仅为了测试方便httpClient.close();}*/} catch (Exception e2) {e2.printStackTrace();}}/*******************get***********************///String getUrl="http://localhost:8083/myapp/api/param?name=123&age=1&time=1500480000000&marriage=false";String getUrl="http://localhost:8083/myapp/api/pojo?name=123&age=1&time=1500480000000&marriage=false";HttpGet httpget = new HttpGet(getUrl);try {response = httpClient.execute(httpget);HttpEntity httpEntity = response.getEntity();if (httpEntity != null) {String result = EntityUtils.toString(httpEntity);System.out.println(result);// 确保HTTP响应内容全部被读出或者内容流被关闭EntityUtils.consume(httpEntity);}} catch (Exception e) {e.printStackTrace();} finally {httpget.releaseConnection();try {if (response != null) {response.close();;}if (httpClient != null) {httpClient.close();}} catch (Exception e2) {e2.printStackTrace();}}}private static List<NameValuePair> getPostparams() {// 放入一个List集合中List<NameValuePair> list = new ArrayList<>();list.add(new BasicNameValuePair("name", "张三"));list.add(new BasicNameValuePair("age", "1"));list.add(new BasicNameValuePair("marriage", "false"));list.add(new BasicNameValuePair("time", "1500480000000"));return list;}private static String getStringEntity() {// 放入一个List集合中return "{'name':'张三','age':'1,'marriage':'false','time':'1500480000000'}";}}