失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > android与服务器交互总结(json post xUtils Volley)

android与服务器交互总结(json post xUtils Volley)

时间:2024-05-29 04:41:44

相关推荐

android与服务器交互总结(json post xUtils Volley)

/tu-biao-chart/

从无到有,从来没有接触过Json,以及与服务器的交互。然后慢慢的熟悉,了解了一点。把我学到的东西简单的做个总结,也做个记录,万一以后用到,就不用到处找了。

主要是简单的数据交互,就是字符串的交互,传数据,取数据。刚开始用的普通方法,后来研究了下xUtils框架。

服务器端有人开发,这一块不是我负责,所以我只负责客户端传数据以及接受数据后的处理就OK了。

传递数据的形式,主要是看服务端的接口怎么写,服务器是接受JSON字符串,还是要form表单格式(我认为form表单格式就是键值对)。

xUtils:

不需要关联library,就下载jar包,复制到libs下就可以了,这是下载地址:/detail/u012975370/9003713

还有就是,你如果想使用library到自己的项目下,注意一点主项目文件和library库文件,必须在同一个文件夹目录下,否则运行项目是报错的

/dj0379/article/details/38356773

项目原码地址:/wyouflf/xUtils

/gb/share/4360.htm

Volley:

初识Volley的基本用法:/view-detail-70211.html

使用Volley加载网络图片:/view-detail-70212.html

定制自己的Request:/view-detail-70213.html

还有一些框架:KJFeame和Afinal

KJFrame:

/kymjs/KJFrameForAndroid

/article/Android-orm-kjframeforandroid.html

1.要发送到服务器端的是以JSON字符串的形式发送的。(下面的格式)

[java]view plaincopy {"device":"hwG620S-UL00","brand":"HUAWEI","model":"G620S-UL00","imei":"865242025001258","romversion":"G620S-UL00V100R001C17B264"}[java]view plaincopy privatevoidsendData1(){newThread(newRunnable(){@Overridepublicvoidrun(){Log.i(TEST_TAG,"2222");try{HttpPostpost=newHttpPost(ACTIVATE_PATH);//post请求//先封装一个JSON对象JSONObjectparam=newJSONObject();param.put("romversion",serviceInfoMap.get("romversion"));param.put("brand",serviceInfoMap.get("brand"));param.put("model",serviceInfoMap.get("model"));param.put("device",serviceInfoMap.get("device"));param.put("imei",serviceInfoMap.get("imei"));//绑定到请求EntryStringEntityse=newStringEntity(param.toString(),"utf-8");post.setEntity(se);Log.i(TEST_TAG,"JSON为--->"+param.toString());//JSON为--->//{"device":"hwG620S-UL00","brand":"HUAWEI","model":"G620S-UL00","imei":"8<spanstyle="white-space:pre"></span>//65242025001258","romversion":"G620S-UL00V100R001C17B264"}//发送请求HttpParamsparams=newBasicHttpParams();DefaultHttpClientlocalDefaultHttpClient=newDefaultHttpClient(params);localDefaultHttpClient.getParams().setParameter("http.connection.timeout",Integer.valueOf(30000));localDefaultHttpClient.getParams().setParameter("http.socket.timeout",Integer.valueOf(30000));HttpResponseresponse=localDefaultHttpClient.execute(post);//得到应答的字符串,这也是一个JSON格式保存的数据StringretStr=EntityUtils.toString(response.getEntity());//生成JSON对象JSONObjectresult=newJSONObject(retStr);intstatus_value=response.getStatusLine().getStatusCode();Log.i(TEST_TAG,""+status_value);StringstatusValue="";statusValue=result.getString("status");Log.i(TEST_TAG,statusValue);if(!statusValue.equals("")){//如果不为空,说明取到了数据,然后就先关闭进去条mHandler.sendEmptyMessage(CLOSE_DIALOG);//然后判断值是否==1,来决定弹出哪个dialog//激活成功,就把值传到系统的contentprovider,然后永久保存if(Integer.parseInt(statusValue)==1){mHandler.sendEmptyMessage(SHOW_SUCCESS);//将值设置成1Settings.System.putInt(getContentResolver(),SETTING_MODIFY_NAME,1);}else{//只要是不为1外的其他值,都算失败,弹出失败的dialogmHandler.sendEmptyMessage(SHOW_FAILURE);}}}catch(UnsupportedEncodingExceptione){e.printStackTrace();}catch(ClientProtocolExceptione){e.printStackTrace();mHandler.sendEmptyMessage(CONTENT_STATUS);}catch(SocketExceptione){mHandler.sendEmptyMessage(CONTENT_STATUS);}catch(IOExceptione){mHandler.sendEmptyMessage(CONTENT_STATUS);e.printStackTrace();}catch(JSONExceptione){mHandler.sendEmptyMessage(CONTENT_STATUS);e.printStackTrace();}}}).start();}

2.以form表单的格式发送到服务端

将传递的数据打印出来,格式是这样的,和json串是不一样的。[romversion=G620S-UL00V100R001C17B264, brand=HUAWEI, model=G620S-UL00, device=hwG620S-UL00, imei=865242024756522]

[java]view plaincopy privatevoidsendData1(){newThread(newRunnable(){@Overridepublicvoidrun(){Log.i(TEST_TAG,"2222");try{HttpPostpost=newHttpPost(ACTIVATE_PATH);//post请求//设置添加对象List<NameValuePair>paramsForm=newArrayList<NameValuePair>();paramsForm.add(newBasicNameValuePair("romversion",serviceInfoMap.get("romversion")));paramsForm.add(newBasicNameValuePair("brand",serviceInfoMap.get("brand")));paramsForm.add(newBasicNameValuePair("model",serviceInfoMap.get("model")));paramsForm.add(newBasicNameValuePair("device",serviceInfoMap.get("device")));paramsForm.add(newBasicNameValuePair("imei",serviceInfoMap.get("imei")));Log.i(TEST_TAG,paramsForm.toString());post.setEntity(newUrlEncodedFormEntity(paramsForm,HTTP.UTF_8));//发送请求HttpParamsparams=newBasicHttpParams();DefaultHttpClientlocalDefaultHttpClient=newDefaultHttpClient(params);localDefaultHttpClient.getParams().setParameter("http.connection.timeout",Integer.valueOf(30000));localDefaultHttpClient.getParams().setParameter("http.socket.timeout",Integer.valueOf(30000));HttpResponseresponse=localDefaultHttpClient.execute(post);//得到应答的字符串,这也是一个JSON格式保存的数据StringretStr=EntityUtils.toString(response.getEntity());//生成JSON对象JSONObjectresult=newJSONObject(retStr);intstatus_value=response.getStatusLine().getStatusCode();Log.i(TEST_TAG,""+status_value);StringstatusValue="";statusValue=result.getString("status");Log.i(TEST_TAG,"status:"+statusValue);Log.i(TEST_TAG,"datatime:"+result.getString("datatime"));Log.i(TEST_TAG,"message:"+result.getString("message"));if(!statusValue.equals("")){//如果不为空,说明取到了数据,然后就先关闭进去条mHandler.sendEmptyMessage(CLOSE_DIALOG);//然后判断值是否==1,来决定弹出哪个dialog//激活成功,就把值传到系统的contentprovider,然后永久保存if(Integer.parseInt(statusValue)==1){//将值设置成1。需要加权限Settings.System.putInt(getContentResolver(),SETTING_MODIFY_NAME,1);mHandler.sendEmptyMessage(SHOW_SUCCESS);}else{//只要是不为1外的其他值,都算失败,弹出失败的dialogmHandler.sendEmptyMessage(SHOW_FAILURE);}}}catch(UnsupportedEncodingExceptione){e.printStackTrace();mHandler.sendEmptyMessage(SHOW_FAILURE);mHandler.sendEmptyMessage(CONTENT_STATUS);}catch(ClientProtocolExceptione){e.printStackTrace();mHandler.sendEmptyMessage(SHOW_FAILURE);mHandler.sendEmptyMessage(CONTENT_STATUS);}catch(SocketExceptione){mHandler.sendEmptyMessage(SHOW_FAILURE);mHandler.sendEmptyMessage(CONTENT_STATUS);}catch(IOExceptione){mHandler.sendEmptyMessage(SHOW_FAILURE);mHandler.sendEmptyMessage(CONTENT_STATUS);e.printStackTrace();}catch(JSONExceptione){mHandler.sendEmptyMessage(SHOW_FAILURE);mHandler.sendEmptyMessage(CONTENT_STATUS);e.printStackTrace();}}}).start();}

3.xUtils框架的post上传数据,表单格式

[java]view plaincopy /***表单格式传送(键值对)*/privatevoidxUtilsFrame(){RequestParamsparams=newRequestParams();params.addBodyParameter("romversion",serviceInfoMap.get("romversion"));params.addBodyParameter("brand",serviceInfoMap.get("brand"));params.addBodyParameter("model",serviceInfoMap.get("model"));params.addBodyParameter("device",serviceInfoMap.get("device"));params.addBodyParameter("imei",serviceInfoMap.get("imei"));Log.i(TEST_TAG,params.getEntity().toString());HttpUtilshttp=newHttpUtils();http.configCurrentHttpCacheExpiry(1000*10);http.send(HttpMethod.POST,ACTIVATE_PATH,params,newRequestCallBack<String>(){@OverridepublicvoidonSuccess(ResponseInfo<String>responseInfo){Log.i(TEST_TAG,"接收到的结果为---》"+responseInfo.result);Log.i(TEST_TAG,"请求码为--->"+responseInfo.statusCode);try{JSONObjectjsonObject=newJSONObject(responseInfo.result);Log.i(TEST_TAG,jsonObject.getString("message"));if(jsonObject.getString("status").equals("1")){mHandler.sendEmptyMessage(CLOSE_DIALOG);mHandler.sendEmptyMessage(SHOW_SUCCESS);Settings.System.putInt(getContentResolver(),SETTING_MODIFY_NAME,1);}else{mHandler.sendEmptyMessage(CLOSE_DIALOG);mHandler.sendEmptyMessage(SHOW_FAILURE);}}catch(JSONExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}@OverridepublicvoidonFailure(HttpExceptionerror,Stringmsg){Toast.makeText(getApplicationContext(),"失败了",Toast.LENGTH_LONG).show();}});}

4.xUtils框架,json数据格式

[java]view plaincopy /***发送json字符串*/privatevoidxUtilsFrame2(){try{RequestParamsparams=newRequestParams();//先封装一个JSON对象JSONObjectparam=newJSONObject();param.put("romversion",serviceInfoMap.get("romversion"));param.put("brand",serviceInfoMap.get("brand"));param.put("model",serviceInfoMap.get("model"));param.put("device",serviceInfoMap.get("device"));param.put("imei",serviceInfoMap.get("imei"));StringEntitysEntity=newStringEntity(param.toString(),"utf-8");params.setBodyEntity(sEntity);Log.i(TEST_TAG,"params-->"+params.toString());//params-->com.lidroid.xutils.http.RequestParams@41c74e10Log.i(TEST_TAG,"param-->"+param.toString());//param-->{"device":"hwG620S-UL00","brand":"HUAWEI","model":"G620S-UL00","imei":"865242024756522","romversion":"G620S-UL00V100R001C17B264"}Log.i(TEST_TAG,"param-entity-->"+sEntity.toString());//param-entity-->org.apache.http.entity.StringEntity@41c482f0HttpUtilshttp=newHttpUtils();http.configCurrentHttpCacheExpiry(1000*10);http.send(HttpMethod.POST,ACTIVATE_PATH,params,newRequestCallBack<String>(){@OverridepublicvoidonSuccess(ResponseInfo<String>responseInfo){Log.i(TEST_TAG,"接收到的结果为---》"+responseInfo.result);//接收到的结果为---》{"status":"2","datatime":1437444596,"message":"参数无效!"}Log.i(TEST_TAG,"请求码为--->"+responseInfo.statusCode);try{JSONObjectjsonObject=newJSONObject(responseInfo.result);Log.i(TEST_TAG,jsonObject.getString("message"));if(jsonObject.getString("status").equals("1")){mHandler.sendEmptyMessage(CLOSE_DIALOG);mHandler.sendEmptyMessage(SHOW_SUCCESS);Settings.System.putInt(getContentResolver(),SETTING_MODIFY_NAME,1);}else{mHandler.sendEmptyMessage(CLOSE_DIALOG);mHandler.sendEmptyMessage(SHOW_FAILURE);}}catch(JSONExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}@OverridepublicvoidonFailure(HttpExceptionerror,Stringmsg){Toast.makeText(getApplicationContext(),"失败了",Toast.LENGTH_LONG).show();}});}catch(JSONExceptione1){//TODOAuto-generatedcatchblocke1.printStackTrace();}catch(UnsupportedEncodingExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}

5.Volley框架:StringRequest,from表单

[java]view plaincopy /***Volley框架:StirngRequest(需要导入Volley.jar包到libs目录下,需要加internet权限)*/privatevoidvolleyFrameSR(){//第一步:创建一个RequestQueue对象finalRequestQueuemQueue=Volley.newRequestQueue(this);//第二步:创建一个StringRequest对象StringRequeststringRequest=newStringRequest(Method.POST,ACTIVATE_PATH,newResponse.Listener<String>(){//服务器响应成功的回调@OverridepublicvoidonResponse(Stringresponse){Log.i(TEST_TAG,"返回结果为--->"+response);try{JSONObjectjsonObject=newJSONObject(response);Log.i(TEST_TAG,"status-->"+jsonObject.getString("status"));Log.i(TEST_TAG,"message-->"+jsonObject.getString("message"));mQueue.cancelAll("StringRequest");mHandler.sendEmptyMessage(SHOW_SUCCESS);mHandler.sendEmptyMessage(CLOSE_DIALOG);}catch(JSONExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}},newResponse.ErrorListener(){//服务器响应失败的回调@OverridepublicvoidonErrorResponse(VolleyErrorerror){Log.e(TEST_TAG,error.getMessage(),error);mHandler.sendEmptyMessage(SHOW_FAILURE);}}){@OverrideprotectedMap<String,String>getParams()throwsAuthFailureError{Map<String,String>map=newHashMap<String,String>();map.put("romversion",serviceInfoMap.get("romversion"));map.put("brand",serviceInfoMap.get("brand"));map.put("model",serviceInfoMap.get("model"));map.put("device",serviceInfoMap.get("device"));map.put("imei",serviceInfoMap.get("imei"));Log.i(TEST_TAG,"发送结果为--->"+map.toString());//发送结果为--->{device=hwG620S-UL00,brand=HUAWEI,//model=G620S-UL00,imei=865242024756522,//romversion=G620S-UL00V100R001C17B264}returnmap;}};stringRequest.setTag("StringRequest");//第三步:将StringRequest对象添加到RequestQueue里面mQueue.add(stringRequest);}

这个写了太多的代码,这是方法的原型:

[java]view plaincopy StringRequeststringRequest=newStringRequest(Method.POST,url,listener,errorListener){@OverrideprotectedMap<String,String>getParams()throwsAuthFailureError{Map<String,String>map=newHashMap<String,String>();map.put("params1","value1");map.put("params2","value2");returnmap;}};

根据我服务器的接受模式,我觉得他发送的结果是form表单格式

6.Volley框架: JsonObjectRequest。

因为它的方法中传递的的请求参数为JsonObject,目前还没有找到传递form格式的方法。

[java]view plaincopy /***Volley框架:JsonObjectRequest*/privatevoidvolleyFrameJR(){//第一步:创建一个RequestQueue对象finalRequestQueuemQueue=Volley.newRequestQueue(this);JsonObjectRequestjsonObjectRequest=newJsonObjectRequest(Method.POST,ACTIVATE_PATH,null,newResponse.Listener<JSONObject>(){@OverridepublicvoidonResponse(JSONObjectresponse){Log.i(TEST_TAG,"返回结果为--->"+response.toString());try{//JSONObjectjsonObject=newJSONObject(response);Log.i(TEST_TAG,"status-->"+response.getString("status"));Log.i(TEST_TAG,"message-->"+response.getString("message"));mHandler.sendEmptyMessage(SHOW_SUCCESS);mHandler.sendEmptyMessage(CLOSE_DIALOG);}catch(JSONExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}},newResponse.ErrorListener(){@OverridepublicvoidonErrorResponse(VolleyErrorerror){Log.e(TEST_TAG,error.getMessage(),error);mHandler.sendEmptyMessage(SHOW_FAILURE);}}){@OverrideprotectedMap<String,String>getPostParams()throwsAuthFailureError{Map<String,String>map=newHashMap<String,String>();map.put("romversion",serviceInfoMap.get("romversion"));map.put("brand",serviceInfoMap.get("brand"));map.put("model",serviceInfoMap.get("model"));map.put("device",serviceInfoMap.get("device"));map.put("imei",serviceInfoMap.get("imei"));Log.i(TEST_TAG,"发送结果为--->"+map.toString());returnmap;}};mQueue.add(jsonObjectRequest);//没有这句就无法交互}

这种方式应该可以,好像getParams也可以,因为服务器写的不是接受json格式数据,所以我没法测试。

还有就是去掉重写的方法,不管是getPostParams还是getParams,然后将里面的map集合内容写道,new JsonObjectRequest之前,然后在JsonObject jsonObject = newJsonObject(map),然后将jsonObject作为第三个参数,这样就传递了一个json字符串到服务器。

7.JsonObject和JsonArray

[java]view plaincopy //JsonObject和JsonArray区别就是JsonObject是对象形式,JsonArray是数组形式//创建JsonObject第一种方法JSONObjectjsonObject=newJSONObject();jsonObject.put("UserName","ZHULI");jsonObject.put("age","30");jsonObject.put("workIn","ALI");System.out.println("jsonObject1:"+jsonObject);//创建JsonObject第二种方法HashMap<String,String>hashMap=newHashMap<String,String>();hashMap.put("UserName","ZHULI");hashMap.put("age","30");hashMap.put("workIn","ALI");System.out.println("jsonObject2:"+JSONObject.fromObject(hashMap));//创建一个JsonArray方法1JSONArrayjsonArray=newJSONArray();jsonArray.add(0,"ZHULI");jsonArray.add(1,"30");jsonArray.add(2,"ALI");System.out.println("jsonArray1:"+jsonArray);//创建JsonArray方法2ArrayList<String>arrayList=newArrayList<String>();arrayList.add("ZHULI");arrayList.add("30");arrayList.add("ALI");System.out.println("jsonArray2:"+JSONArray.fromObject(arrayList));//如果JSONArray解析一个HashMap,则会将整个对象的放进一个数组的值中System.out.println("jsonArrayFROMHASHMAP:"+JSONArray.fromObject(hashMap));//组装一个复杂的JSONArrayJSONObjectjsonObject2=newJSONObject();jsonObject2.put("UserName","ZHULI");jsonObject2.put("age","30");jsonObject2.put("workIn","ALI");jsonObject2.element("Array",arrayList);System.out.println("jsonObject2:"+jsonObject2);

system结果:

[html]view plaincopy jsonObject1:{"UserName":"ZHULI","age":"30","workIn":"ALI"}jsonObject2:{"workIn":"ALI","age":"30","UserName":"ZHULI"}jsonArray1:["ZHULI","30","ALI"]jsonArray2:["ZHULI","30","ALI"]jsonArrayFROMHASHMAP:[{"workIn":"ALI","age":"30","UserName":"ZHULI"}]jsonObject2:{"UserName":"ZHULI","age":"30","workIn":"ALI","Array":["ZHULI","30","ALI"]}[html]view plaincopy </pre><prename="code"class="html"style="font-size:13px;margin-top:0px;margin-bottom:0px;padding:0px;white-space:pre-wrap;word-wrap:break-word;line-height:19.5px;background-color:rgb(254,254,242);">[html]view plaincopy <spanstyle="font-size:24px;">android读取json数据(遍历JSONObject和JSONArray)</span>[html]view plaincopy <prename="code"class="java">publicStringgetJson(){StringjsonString="{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack\"},{\"name\":\"lucy\"}]}";//json字符串try{JSONObjectresult=newJSONObject(jsonstring);//转换为JSONObjectintnum=result.length();JSONArraynameList=result.getJSONArray("name");//获取JSONArrayintlength=nameList.length();Stringaa="";for(inti=0;i<length;i++){//遍历JSONArrayLog.d("debugTest",Integer.toString(i));JSONObjectoj=nameList.getJSONObject(i);aa=aa+oj.getString("name")+"|";}Iterator<?>it=result.keys();Stringaa2="";Stringbb2=null;while(it.hasNext()){//遍历JSONObjectbb2=(String)it.next().toString();aa2=aa2+result.getString(bb2);}returnaa;}catch(JSONExceptione){thrownewRuntimeException(e);}}

8.生成数组json串

我想要生成的json串为: {

"languages": [//应用市场所支持的语种信息

{

"name":"汉语",

"code":"hy",

"selected":"true"

},

{

"name":"蒙古语",

"code":"mn"

"selected":"false"

}

],

"applist_versioncode":"0",

"applist_num":"2", } 代码如下:[java]view plaincopy privatevoidcreateJsonData(){try{//存放总的json数据的容器JSONObjectjsonObject=newJSONObject();/**首先,总的josn的第一条的key是languages,他的value是一个数组,数组有两个元素,所以,*languages对应的value是一个JsonArray对象*///此时生成一个jsonarray来存放language的值的数组JSONArrayjsonArrayLang=newJSONArray();//首先将language的第一条数据,生成jsonObject对象JSONObjectjoLang0=newJSONObject();joLang0.put("name","汉语");joLang0.put("code","hy");joLang0.put("selected","true");//此时,将数组的第一组数据添加到jsonarray中jsonArrayLang.put(0,joLang0);//首先将language的第二条数据,生成jsonObject对象JSONObjectjoLang1=newJSONObject();joLang1.put("name","蒙古语");joLang1.put("code","mn");joLang1.put("selected","false");//此时,将数组的第一组数据添加到jsonarray中jsonArrayLang.put(1,joLang1);//此时,langauge的值已经生成,就是jsonarraylang这个数组格式的数据//然后,将其添加到总的jsonobject中jsonObject.put("languages",jsonArrayLang);//添加总jsonobject容器的第二条数据,"applist_versioncode":"0",jsonObject.put("applist_versioncode","0");//添加总jsonobject容器的第三条数据,"applist_num":"2",jsonObject.put("applist_num","2");System.out.println(jsonObject.toString());}catch(JSONExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}} 最后输出结果为

9.修改json串(带数组)

[java]view plaincopy Stringstt="{\"languages\":[{\"name\":\"汉语\",\"code\":\"hy\"},"+"{\"name\":\"蒙古语\",\"code\":\"mn\"}]}";[java]view plaincopy <spanstyle="white-space:pre"></span>try{JSONObjectjsonObject=newJSONObject(stt);System.out.println("修改之前---->"+jsonObject.toString());JSONArrayjsonArray=jsonObject.getJSONArray("languages");System.out.println("修改之前---->"+jsonArray.toString());System.out.println("jsonArray.length()---->"+jsonArray.length());for(inti=0;i<jsonArray.length();i++){JSONObjectjsonObject2=(JSONObject)jsonArray.opt(i);System.out.println("jsonObject2---->"+i+"-----"+jsonArray.toString());if(i==(jsonArray.length()-1)){System.out.println("修改之前---->");jsonObject2.put("name","法国与");jsonArray.put(i,jsonObject2);}}jsonArray.put(jsonArray.length(),(JSONObject)jsonArray.opt(jsonArray.length()-1));jsonObject.put("languages",jsonArray);System.out.println("修改之后---->"+jsonObject.toString());}catch(JSONExceptione){e.printStackTrace();}

修改json串,就需要一层一层读出来,然后key值存在的时候,直接put新值,就会直接替换掉,然后在一层一层添加回去。这样就可以了

如果觉得《android与服务器交互总结(json post xUtils Volley)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。