no-image

org.apache.http.client.methods.HttpPost 兩種訊息體形式 —— UrlEncodedFormEntity 和 StringEntity

                                    

做APP,小程式就上開源眾包。世界盃期間免費領2600元啟動金。
>>>
  

一、UrlEncodedFormEntity

程式碼示例:

//設定請求方式與引數
URI uri = new URI(uriStr);
HttpPost httpPost = new HttpPost(uri);
httpPost.getParams().setParameter("http.socket.timeout", new Integer(500000));
httpPost.setHeader("Content-type", "text/plain; charset=UTF-8");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
httpPost.setHeader("IConnection", "close");

List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("KEY1", "VALUE1"));
//...
httpPost.setEntity(new UrlEncodedFormEntity(nvps));

//執行請求
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("Content-Encoding", "UTF-8");
HttpResponse response = httpclient.execute(httpPost);

//獲取返回
HttpEntity entity = response.getEntity();
BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
  buffer.append(line);
}
return buffer.toString();

使用 UrlEncodedFormEntity 來設定 body,訊息體內容類似於“KEY1=VALUE1&KEY2=VALUE2&…”這種形式,服務端接收以後也要依據這種協議形式做處理。

二、StringEntity
有時候我們不想使用上述格式來傳值,而是想使用json格式來設定body,就可以使用這個類的例項。

程式碼示例:

JSONObject jsonObject = new JSONObject();
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
httpPost.setEntity(new StringEntity(jsonObject.toString()));

其實,採用 StringEntity 就是形式比較自由了,除了json,你也可以使用其它任意的字串,只要服務端能做相應處理即可。


(adsbygoogle = window.adsbygoogle || []).push({});

function googleAdJSAtOnload() {
var element = document.createElement(“script”);
element.src = “//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”;
element.async = true;
document.body.appendChild(element);
}
if (window.addEventListener) {
window.addEventListener(“load”, googleAdJSAtOnload, false);
} else if (window.attachEvent) {
window.attachEvent(“onload”, googleAdJSAtOnload);
} else {
window.onload = googleAdJSAtOnload;
}