Android StringEntity() 和 UrlEncodedFormEntity() 的区别

简介: <p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; color:rgb(85,85,85); font-family:'microsoft yahei'; font-size:15px; line-height:35px"> 今天在做安卓客户端向服务器提交数据的过程中,在组织P

今天在做安卓客户端向服务器提交数据的过程中,在组织POST数据时,用了UrlEncodedFormEntity()这个方法,但是后台报错,说是无法解析json内容。

按照本来的想法,向后台发送的是 json 格式的内容,里面有参数和值,供后台程序处理,形式如下“:

{"content":"鍛樺伐涓氬姟姘村钩涓嶈冻","townId":"14","companyId":"8","date":"2014-12-27","supervisor":"鑻忚礊鏄?,"userId":0}

但是,用UrlEncodedFormEntity()方法组织的数据发送到服务器却是如下形式:

companyId=8&townId=14&date=2014-12-27&supervisor=%E8%B0%A2%E9%95%BF%E5%BB%B7&content=%E5%91%98%E5%B7%A5%E4%B8%9A%E5%8A%A1%E6%B0%B4%E5%B9%B3%E6%9C%89%E5%BE%85%E6%8F%90%E9%AB%98&userId=0

很显然,是普通的键值对,不是json,所以后台无法接受。

后来改用 StringEntity()方法组织数据,数据的形式就非常自由了,可以组织成自己想要的任何形式,问题解决。

下面来比较一下两种方法的使用:

1. UrlEncodedFormEntity() 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. List<NameValuePair> pairs = new ArrayList<NameValuePair>();  
  2.   
  3. NameValuePair pair1 = new BasicNameValuePair("supervisor", supervisorEt.getEditableText().toString());  
  4. NameValuePair pair2 = new BasicNameValuePair("content", superviseContentEt.getEditableText().toString());  
  5. NameValuePair pair3 = new BasicNameValuePair("userId", String.valueOf(signedUser.getId()));  
  6.                   
  7. pairs.add(pair1);  
  8. pairs.add(pair2);  
  9. pairs.add(pair3);  
  10.                   
  11. httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8))  


2. StringEntity()

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. JSONObject postData = new JSONObject();  
  2.                   
  3. postData.put("supervisor", supervisorEt.getEditableText().toString());  
  4. postData.put("content", superviseContentEt.getEditableText().toString());  
  5. postData.put("userId", signedUser.getId());  
  6.                   
  7. httpPost.setEntity(new StringEntity(postData.toString(), HTTP.UTF_8));  

可以看出,UrlEncodedFormEntity()的形式比较单一,只能是普通的键值对,局限性相对较大。

而StringEntity()的形式比较自由,只要是字符串放进去,不论格式都可以

目录
相关文章
|
12月前
|
编解码 前端开发 Java
Android drawFunctor 原理及应用
Android drawFunctor 原理及应用
|
前端开发 Java API
Android drawFunctor原理及应用
一. 背景AntGraphic项目Android平台中使用了基于TextureView环境实现GL渲染的技术方案,而TextureView需使用与Activity Window独立的GraphicBuffer,RenderThread在上屏TextureView内容时需要将GraphicBuffer封装为EGLImage上传为纹理再渲染,内存占用较高。为降低内存占用,经仔细调研Android源码,
494 0
|
SQL 编译器 测试技术
Now in Android 16 —— 最新 Android 动态分享
Now in Android 16 —— 最新 Android 动态分享
Now in Android 16 —— 最新 Android 动态分享
|
Android开发
Android几行代码解决键盘遮挡问题
1.scrollTo、scrollBy实现键盘不遮挡; 2.列表中的Edittext,利用假键盘实现键盘不遮挡
2237 0