Several key words:
WebAPI, Android, Apache httpcomponent/httpclient
Problem: No matter how the test, Webapi formbody value is always empty.
The simplest code WebAPI, no authentication
1 //POST api/<controller>2 [HttpPost]3 Public stringPost ([Frombody]stringvalue)4 {5 stringval =value;6 7 Debug.WriteLine (value);8 9 returnvalue;Ten}
The simplest code, Java side, with Stringentity
1 Public Static voidNotauthtestpost ()throwsIOException {2Closeablehttpclient httpclient =Httpclients.createdefault ();3 Try {4HttpPost HP =NewHttpPost ("Http://localhost:8888/api/test");5 6String str= "{' Header ': [{' Summary ': 111, ' Endtime ': 570, ' end_date ': 1431381600, ' resid ': ' sc20150512034635 ', ' starttime ' ': 570, ' ScheduleID ': ' sc155485e5025f3d ', ' machid ': ' sc155485e8044b93 ', ' parentid ': null, ' start_date ': 1431381600}], ' Detail ': [{' perm_modify ': 1, ' owner ': 1, ' perm_delete ': 1, ' resid ': ' sc20150512034635 ', ' MemberID ': ' sc1555070e4d8217 ', ' Invited ': 0},{' perm_modify ': 0, ' owner ': 0, ' Perm_delete ': 0, ' resid ': ' sc20150512034635 ', ' MemberID ': ' Sc155489a07e0e24 ', ' Invited ': 1}]} ";7 8Stringentity SE =NewStringentity (str, contenttype.create ("Application/json", "UTF-8"));9 hp.setentity (SE);Ten One System.out.println (entityutils.tostring (SE)); A -Closeablehttpresponse response1 =NULL; - Try { theResponse1 =Httpclient.execute (HP); - - System.out.println (Response1.getstatusline ()); -Httpentity entity1 =response1.getentity (); + - //Do something useful with the response body + //and ensure it is fully consumed A //Entityutils.consume (entity1); at -String Jsonstr =entityutils.tostring (entity1); - - System.out.println (JSONSTR); - -}Catch(clientprotocolexception e) { in e.printstacktrace (); -}Catch(IOException e) { to e.printstacktrace (); +}finally { - response1.close (); the } * $}finally {Panax Notoginseng httpclient.close (); - } the}
Results:
But the same JSON, using C # httpclient, is perfectly fine.
Care about a bit fiddle capture chart:
Use C # HttpClient: (value can be taken)
Use Java Apache HttpClient (value not to be taken)
Compare to find, in raw view, can see, HttpRequest body is different. is a pair of quotation marks. "".
So add a line to the Java code:
str = "\" "+str +" \ "";
The Webapi end is normal to get value.
It is estimated that there is a deeper solution, so let's take a note.
Use Java httpcomponent/httpclinet to invoke Webapi problem resolution