在这个答案中我使用的是Justin Grammens 发布的示例 http://localtone.blogspot.com/2009/07/post-json-using-android-and-httpclient.html.
关于 JSON
JSON 代表 JavaScript 对象表示法。在 JavaScript 中,属性可以像这样引用object1.name
像这样object['name'];
。本文中的示例使用了这段 JSON。
零件
以电子邮件为键的粉丝对象[电子邮件受保护] /cdn-cgi/l/email-protection作为一个值
{
fan:
{
email : '[email protected] /cdn-cgi/l/email-protection'
}
}
所以对象等价物是fan.email;
or fan['email'];
。两者具有相同的值
的'[email protected] /cdn-cgi/l/email-protection'
.
关于 HttpClient 请求
以下是我们作者用来制作的Http客户端请求 http://developer.android.com/reference/org/apache/http/client/methods/HttpPost.html。我并不声称自己是这方面的专家,因此如果有人有更好的方法来表达某些术语,请随意。
public static HttpResponse makeRequest(String path, Map params) throws Exception
{
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost httpost = new HttpPost(path);
//convert parameters into JSON object
JSONObject holder = getJsonObjectFromMap(params);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString());
//sets the post request as the resulting string
httpost.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
return httpclient.execute(httpost, responseHandler);
}
Map
如果您不熟悉Map
数据结构请看一下Java 地图参考 http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html。简而言之,映射类似于字典或哈希。
private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {
//all the passed parameters from the post request
//iterator used to loop through all the parameters
//passed in the post request
Iterator iter = params.entrySet().iterator();
//Stores JSON
JSONObject holder = new JSONObject();
//using the earlier example your first entry would get email
//and the inner while would get the value which would be '[email protected] /cdn-cgi/l/email-protection'
//{ fan: { email : '[email protected] /cdn-cgi/l/email-protection' } }
//While there is another entry
while (iter.hasNext())
{
//gets an entry in the params
Map.Entry pairs = (Map.Entry)iter.next();
//creates a key for Map
String key = (String)pairs.getKey();
//Create a new map
Map m = (Map)pairs.getValue();
//object for storing Json
JSONObject data = new JSONObject();
//gets the value
Iterator iter2 = m.entrySet().iterator();
while (iter2.hasNext())
{
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}
//puts email and '[email protected] /cdn-cgi/l/email-protection' together in map
holder.put(key, data);
}
return holder;
}
请随意评论关于这篇文章出现的任何问题,或者如果我没有说清楚,或者如果我没有触及你仍然困惑的事情......等等,无论你脑子里真正出现什么。
(如果贾斯汀·格拉门斯不同意,我会删除。但如果不同意,那么感谢贾斯汀对此保持冷静。)