在这个答案中,我使用的是贾斯汀·格莱蒙斯的例子.
关于JSON
JSON代表JavaScript对象表示法。在JavaScript中,属性可以被引用,如下所示object1.name像这样object['name'];..本文中的示例使用了这段JSON。
零件
一个扇对象,电子邮件作为键,foo@bar.com作为值{
fan:
{
email : 'foo@bar.com'
}}
所以对象等价于fan.email;或fan['email'];..两者的价值相同'foo@bar.com'.
关于HttpClient请求
以下是我们的作者过去所做的HttpClient请求..我并不是所有这些方面的专家,所以如果有人有一个更好的方法来表达一些术语,请放心。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数据结构请查看Java地图引用..简而言之,地图类似于字典或散列。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 'foo@bar.com'
//{ fan: { email : 'foo@bar.com' } }
//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 'foo@bar.com' together in map
holder.put(key, data);
}
return holder;}
请随时评论任何有关这篇文章的问题,或者如果我没有说清楚,或者我没有触及到你仍然困惑的事情…。等等,不管你脑子里想的是什么。
(如果贾斯汀·格莱蒙斯不赞成,我就把他拿下。但如果不是的话,那就感谢贾斯汀对此保持冷静。)
更新
我只是碰巧收到了关于如何使用代码的评论,并意识到返回类型中有一个错误。方法签名被设置为返回一个字符串,但在本例中它没有返回任何内容。我将签名更改为HttpResponse,并将在HttpResponse响应体的获取路径变量是url和我更新的,以修复代码中的错误。