httpClient发送http请求时组织post(put)数据

在组织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()的形式比较自由,只要是字符串放进去,不论格式都可以。


实例:

	protected <T> T doHttpPut(String url, String jsonParam, Class<T> classType) {
		HttpPut post = new HttpPut(url);
		try {
			post.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
			StringEntity se = new StringEntity(jsonParam);
	        se.setContentType(CONTENT_TYPE_TEXT_JSON);
	        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
	        post.setEntity(se);
	        
	        System.out.println("aaaaa:"+post.toString());
	        
		} catch (Exception e) {
			// TODO: handle exception
		}
		return genJsonObject(post, classType);
	}


猜你喜欢

转载自blog.csdn.net/no_can_no_bb_/article/details/79075894
今日推荐