Struts2: To play Rest-plugin, learn the way to develop restful service with STRUTS2, and find various errors when calling with C # in Post, but Java, Ajax, including Firefox's Rest There is no problem with the client plug-in test.
This method in the rest service is given first:
1 //post/orders2 PublicHttpheaders Create ()throwsIOException, servletexception {3 Ordersservice.dosave (model);4HttpServletResponse response =servletactioncontext.getresponse ();5HttpServletRequest request =servletactioncontext.getrequest ();6String ContentType = Request.getheader ("Content-type"). toLowerCase ();7 if(Contenttype.startswith ("Application/xml")) {//return to XML view8Response.sendredirect ("orders/" + model.getid () + ". Xml");9}Else if(Contenttype.startswith ("Application/json")) {//return to JSON viewTenResponse.sendredirect ("orders/" + model.getid () + ". JSON"); One}Else{//return to XHTML Page view AResponse.sendredirect ("orders/"); - } - return NULL; the}View Code
The code is not complex, post a string of strings (xml/json/html format can be), automatically mapped to the Order object instance model, and then according to the request Httpheader in Content-type, if it is XML (application /xml), the model corresponding to the XML, if it is JSON (Application/json), then return the model corresponding to the JSON, the other return to the page
Calling code for C #:
1 Static stringpostdatabywebclient (String posturl, String paramdata, string mediatype)2 {3String result =String.Empty;4 Try5 {6 byte[] PostData =Encoding.UTF8.GetBytes (paramdata);7WebClient WebClient =NewWebClient ();8WEBCLIENT.HEADERS.ADD ("Content-type", mediatype);9 byte[] ResponseData = Webclient.uploaddata (NewUri (PostURL),"POST", postdata);Tenresult =Encoding.UTF8.GetString (responsedata); One } A Catch(Exception e) - { - Console.WriteLine (e); theresult =E.message; - } - returnresult; - } + - Static stringPostdatabywebrequest (stringPostURL,stringParamdata, String mediatype) + { A stringresult =string. Empty; atStream newstream =NULL; -StreamReader sr =NULL; -HttpWebResponse response =NULL; - Try - { - byte[] ByteArray =Encoding.UTF8.GetBytes (paramdata); inHttpWebRequest Webreq = (HttpWebRequest) webrequest.create (NewUri (PostURL)); -Webreq.method ="POST"; toWebreq.contenttype =mediatype; +Webreq.contentlength =bytearray.length; -Newstream =Webreq.getrequeststream (); theNewstream.write (ByteArray,0, bytearray.length); *Response =(HttpWebResponse) webreq.getresponse (); $SR =NewStreamReader (response. GetResponseStream (), Encoding.UTF8);Panax Notoginsengresult =Sr. ReadToEnd (); - } the Catch(Exception ex) + { A Console.WriteLine (ex); theresult =Ex. Message; + } - finally $ { $ if(SR! =NULL) - { - Sr. Close (); the } - if(Response! =NULL)Wuyi { the Response. Close (); - } Wu if(Newstream! =NULL) - { About newstream.close (); $ } - } - returnresult; -}View Code
These two commonly used methods of invocation, incredibly full kneeling, the result of the return is a bunch of Java exceptions:
Java.lang.NullPointerException
At Org.apache.struts2.convention.ConventionUnknownHandler.handleUnknownActionMethod ( conventionunknownhandler.java:423)
At Com.opensymphony.xwork2.DefaultUnknownHandlerManager.handleUnknownMethod (Defaultunknownhandlermanager.java : 96)
...
Helpless Baidu a lap, found there is another way to use TcpClient call
1 Static stringPostdatabytcpclient (stringPostURL,stringParamdata, String mediatype)2 {3String result =String.Empty;4TcpClient Clientsocket =NULL;5Stream Readstream =NULL;6 Try7 {8Clientsocket =NewTcpClient ();9Uri uri =NewUri (posturl);Ten Clientsocket.connect (URI. Host, URI. Port); OneStringBuilder requestheaders =NewStringBuilder ();//used to save HTML protocol header information ARequestheaders.appendformat ("{0} {1} http/1.1\r\n","POST", URI. Pathandquery); -Requestheaders.appendformat ("connection:close\r\n"); -Requestheaders.appendformat ("host:{0}\r\n", URI. Host); theRequestheaders.appendformat ("content-type:{0}\r\n", mediatype); -Requestheaders.appendformat ("\ r \ n"); -Requestheaders.append (Paramdata +"\ r \ n"); -Encoding Encoding =Encoding.UTF8; + byte[] Request =encoding. GetBytes (Requestheaders.tostring ()); - clientSocket.Client.Send (request); +Readstream =Clientsocket.getstream (); AStreamReader sr =NewStreamReader (Readstream, Encoding.UTF8); atresult =Sr. ReadToEnd (); - } - Catch(Exception e) - { - Console.WriteLine (e); -result =E.message; in } - finally to { + if(Readstream! =NULL) - { the readstream.close (); * } $ if(Clientsocket! =NULL)Panax Notoginseng { - clientsocket.close (); the } + } A returnresult; the}View Code
Finally the call succeeds, but since the Java side is redirected with Sendredirect on the client, the result of this method is as follows:
http/1.1 302 Found
server:apache-coyote/1.1
Location:http://localhost/struts2-rest-ex/rest/orders/230.xml
content-length:0
Date:mon, Oct 03:18:56 GMT
Connection:close
is a bunch of HTTP header text, can only curve the salvation, the location: After the part (that is, the redirected URL), take out to get the request again, there is a pit, the URL returned, the port was lost, the correct redirect URL should be:
http://localhost: 8080/struts2-rest-ex/rest/orders/230.xml
Manually put the port together, get again, and finally return to the correct
C # Post calls to Struts Rest-plugin service issues