put方法和patch方法的区别

在restful风格的api中,put/patch方法一般用于更新数据。在项目的代码中,使用的是httpclient 4.5,是这样写的:
protected jsonobject dohttpurirequest(httpurirequest httpurirequest) {
jsonobject result = null;
httpclient httpclient = httpclients.createdefault();
try {
httpresponse httpresponse = httpclient.execute(httpurirequest);
statusline responsestatusline = httpresponse.getstatusline();
int statuscode = responsestatusline.getstatuscode();
if (statuscode == 200) {
httpentity responseentity = httpresponse.getentity();
string jsonstring = entityutils.tostring(responseentity, character_set);
result = new jsonobject(jsonstring);
entityutils.consume(responseentity);
} else {
// error handling
}
} catch (ioexception e) {
e.printstacktrace();
return onlocalerror(e);
}
return result;
}
protected jsonobject dohttppatch(string uri, map params) {
jsonobject result = null;
httppatch httppatch = new httppatch(uri);
list nvps = constructnvps(params); // constructing name-value pair
try {
httppatch.setentity(new urlencodedformentity(nvps, character_set));
result = dohttpurirequest(httppatch);
} catch (unsupportedencodingexception e) {
e.printstacktrace();
return onlocalerror(e);
}
return result;
}
其中dohttpurirequest()是一个处理发送请求的工具函数,dohttppatch()是具体处理数据的函数。
可见写法和一个普通的post请求差不多,只是将httppost换成httppatch。
可是在server端,比如在params中有一个参数叫key,值是value,在controller里面,能识别到这是一个patch方法,可是key的值是null。就是servlet不能从form里面获取参数。
google查了一下原因,大体是说patch这个方法很新,就算到tomcat 7.0.39也都不支持。那怎么破呢?有两个办法:

  1. 用uri来请求
    既然不能使用form来获取参数,那就写在uri的尾巴吧:
    protected jsonobject dohttppatchwithuri(string uri, map params) {
    jsonobject result = null;
    uribuilder uribuilder = new uribuilder();
    uribuilder.setpath(uri);
    uribuilder.setparameters(constructnvps(params));
    try {
    uri builturi = uribuilder.build();
    httppatch httppatch = new httppatch(builturi);
    result = dohttpurirequest(httppatch);
    } catch (urisyntaxexception e) {
    e.printstacktrace();
    return onlocalerror(e);
    }
    return result;
    }
    使用了这种做法,servlet可以获得参数了。
    这个方法有一个问题。就是即使key是null值,在uri的参数也会带上。在servlet里面接收,key的值会变成”“(空字符串)。这样在restful风格api里面会有歧义:究竟是不更新,还是更新成空字符串呢?
  2. 在web.xml中加入一个filter
    另一种做法是保持使用上面post风格的方法,在web.xml中加入一个filter:
    httpputformcontentfilter
    org.springframework.web.filter.httpputformcontentfilter
    httpputformcontentfilter
    springwebmvcdispatcher
    其中springwebmvcdispatcher是servlet的名字。
    filter的工作是从request body的form data里面读取数据,然后包装成一个servletrequest,使得servletrequest.getparameter*()之类的方法可以读取到数据。
原文地址:https://www.cnblogs.com/Ran0707-0721/p/14215451.html