Android中如何使用JSON来实现客户端和服务器的交互 第3页
123. protectedvoidpack(Stringurl)throwsException{
124. httpClient=newDefaultHttpClient();
125. httpRequest=newHttpPost(url);
126.
127. httpRequest.setEntity(newUrlEncodedFormEntity(nameValuePair));
128. response=httpClient.execute(httpRequest);
129. }
130.
131. /**
132. *得到返回数据
133. *
134.
*@paramurl 135.
*@return 136.
*@throwsException 137. */
138. protectedvoidparse()throwsException{
139. //TODO状态处理500200
140. if (response.getStatusLine().getStatusCode()== 200 ){
141.
142. BufferedReaderbufferedReader2=newBufferedReader(
143. newInputStreamReader(response.getEntity().getContent()));
144. for (Strings=bufferedReader2.readLine();s!= null ;s=bufferedReader2
145. .readLine()){
146. sb.append(s);
147. }
148. }
149. }
150.
151. /**
152. *向服务器发送信息
153. *
154.
*@paramkey 155.
*@paramvalue 156. */
157. publicvoidaddNameValuePair(Stringkey,Stringvalue){
158. nameValuePair.add(newBasicNameValuePair(key,value));
159. }
160.
161. /**
162. *返回JSONObject对象数据模型
163. *
164. 辣,文-论'文:网
http://www.751com.cn 166. */
167. publicJSONObjectgetJSON()throwsJSONException{
168. returnnewJSONObject(sb.toString());
169. }
170.
171.}
第四步 书写登陆协议
这里只是模拟登陆使用的一个类
1.packagecom.jclick.protocol;
2.
3.importorg.json.JSONObject;
4.
5.importcom.jclick.bean.User;
6.
7.publicclassLoginProtocolextendsBaseProtocol{
8.
9.privatefinalstaticStringURL= "
http://localhost:8080/test/login" ;
10.
11.publicbooleancheckLogin(Userusr){
12.try {
13.pack(URL);
14.parse();
15.JSONObjectobj= this .getJSON();
16.if (obj.getString( "result" ).equals( "failed" )){
17.returnfalse;
18.} else {
19.returntrue;
20.}
21.} catch (Exceptione){
22.e.printStackTrace();
23.returnfalse;
24.}
25.}
26.
27.}
28.
29.packagecom.jclick.protocol;
30.
31.importorg.json.JSONObject;
32.
33.importcom.jclick.bean.User;
34.
35.publicclassLoginProtocolextendsBaseProtocol{
36.
37. privatefinalstaticStringURL= "辣,文-论'文:网
http://www.751com.cn 38.
39. publicbooleancheckLogin(Userusr){
40. try {
41. pack(URL);
42. parse();
43. JSONObjectobj= this .getJSON();
44. if (obj.getString( "result" ).equals( "failed" )){
45. returnfalse;
46. } else {
47. returntrue;
48. }
49. } catch (Exceptione){
50. e.printStackTrace();
51. returnfalse;
52. }
53. }
54.
55.}
然后是User实体类,主要用于保存用户信息:
1.packagecom.jclick.bean;
2.
3.publicclassUser{
4.privateStringusername;
5.privateStringpassword;
6.publicStringgetUsername(){
7.returnusername;
8.}
9.publicvoidsetUsername(Stringusername){
10.this .username=username;
上一页 [1] [2] [3]
Android中如何使用JSON来实现客户端和服务器的交互 第3页下载如图片无法显示或论文不完整,请联系qq752018766