First, the goal
The Android client sends a JSON-formatted HTTP request, expecting a JSON feedback from the server.
1. The JSON format sent by the client is:
{"Data": "Valuestring"}
2. JSON format sent by the server:
{
"ErrorCode": "Valuestring",
"Entries": [
{
"Name": "Sea Fishing",
"Phone": "18800000110",
"url": "Http://cater.haidilao.com/Cater/wap/index.action"
},
{
"Name": "Mount Emei",
"Phone": "18800000119",
"url": "Http://51youhui.baidu.com/emeishan"
},
...
{
"Name": "Public Education",
"Phone": "18800000666",
"url": "Http://m.offcn.com"
}
]
}
3. The entity class types that are mapped in JSON are defined as follows:
Public classEntry {//User name PrivateString name; //User Number PrivateString Phone; //User Homepage URL PrivateString URL; PublicEntry () {} PublicEntry (string name, string phone, string url) {Super(); This. Name =name; This. Phone =phone; This. url =URL; } PublicString GetUrl () {returnURL; } Public voidseturl (String url) { This. url =URL; } Public BooleanIssupportzhidahao () {return This. url! =NULL; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString Getphone () {returnphone; } Public voidSetphone (String phone) { This. Phone =phone; }}
Second, the reference package prerequisites:
1. Android Client:
Since no additional packages are available, the JSON packages that you rely on are included under the Org.json package of the Android SDK.
2. Service side:
Commons-beanutils-1.9.2.jar
Commons-collections-3.2.1.jar
Commons-lang-2.6.jar
Commons-logging-1.2.jar
Ezmorph-1.0.6.jar
Json-lib-2.4-jdk15.jar
Download reference: http://www.mvnrepository.com/
Third, the client code
1. Code when the Android client sends the request (using HttpClient):
//the project URL where the test server resides FinalString Server_url = "Http://172.22.148.49:8080/TestHttp/TestHttp"; HttpPost postrequest=NewHttpPost (Server_url); //construct the JSON string for the requestJsonobject para =NewJsonobject (); Para.put ("Data", NUMSTR); Stringentity Entity=NewStringentity (Para.tostring (), "Utf-8"); HttpClient Client=Newdefaulthttpclient (); Postrequest.setentity (entity); HttpResponse Response= Client.execute (postrequest);
The 2.android client accepts and resolves the JSON value of the service-side return request:
list<entry> items =NewArraylist<entry>(); //read the return value of all character formatting from responseString entitystring =entityutils.tostring (Response.getentity ()); //Map The return value of character formatting to a JSON objectJsonobject resjsonobj =NewJsonobject (entitystring); //attempt to read the StatusCode field in the returned JSON value if(resjsonobj.getstring (statusCode) = =NULL||resjsonobj.getstring (Status_code). IsEmpty ()|| !resjsonobj.getstring (Status_code). Equals ("OK")) { return; } //attempt to parse all JSON objects returned as JSON arraysJsonarray Entiesarray = Resjsonobj.getjsonarray ("Entries"); for(inti = 0; I < entiesarray.length (); i++) {Jsonobject json=Entiesarray.getjsonobject (i); Item=NewEntry (); Item.setname (Json.getstring ("Name")); Item.setphonenum (Json.getstring ("Phone")); Item.sethomepagesites (json.getstring ("url")); Items.Add (item); }
Iv. Service-side code
1. Read the HTTP request from the client and parse out the JSON parameters (in the servlet's Dopost method):
//agree to parameters in HTTP requestString Acceptjson = ""; BufferedReader BR=NewBufferedReader (NewInputStreamReader (ServletInputStream) Request.getinputstream (),"Utf-8")); StringBuffer SB=NewStringBuffer (""); String temp; while(temp = Br.readline ())! =NULL) {sb.append (temp); } br.close (); Acceptjson=sb.tostring (); String Data= ""; Jsonobject Jo=Jsonobject.fromobject (Acceptjson); Data= jo.getstring ("Data"); System.out.println ("The client has a parameter of" + data ";
2. After the server finishes processing the values specified in the request parameters, it decides to return the JSON-formatted JSON string we agreed on above:
//creating a JSON root objectJsonobject Mjson =NewJsonobject (); //Creates a JSON object with a JSON array containing the values of the entity classes .Jsonarray Jsonarray =NewJsonarray (); Mjson.put ("StatusCode", "OK"); for(Entry entry:entries) {if(!Entry.getphone (). Contains (data))Continue; Jsonobject JSON=NewJsonobject (); Json.put ("Name", Entry.getname ()); Json.put ("Phone", Entry.getphone ()); Json.put ("url", Entry.geturl ()); Jsonarray.add (JSON); } mjson.put ("Entries", Jsonarray); Response.setcontenttype ("Text/html;charset=utf-8"); Response.getwriter (). Write (mjson.tostring ());
V. Precautions (to be continued ...) )
1. Encoding format issues
2. HttpClient request concurrency problem in Android
Detailed understanding and setting of some parameters in 3.http request
Android HTTP POST request with JSON string