在这个答案中,我使用的是example posted by Justin Grammens。
关于 JSON
JSON 代表 JavaScript 对象表示法。在 JavaScript 中,属性可以像 object1.name 和 object['name']; 一样被引用。文章中的示例使用了这一点 JSON。
零件
以 email 为键、foo@bar.com 为值的粉丝对象
{
fan:
{
email : 'foo@bar.com'
}
}
所以对象等价物将是fan.email; 或fan['email'];。两者将具有相同的值
'foo@bar.com'.
关于 HttpClient 请求
以下是我们作者用来制作HttpClient Request的内容。我并没有声称自己是这方面的专家,所以如果有人有更好的方式来表达一些术语,请随意。
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 Map reference。简而言之,映射类似于字典或哈希。
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;
}
请随时对关于这篇文章的任何问题发表评论,或者如果我没有说清楚,或者如果我没有触及你仍然困惑的东西......等等,无论你真的想到了什么。
(如果 Justin Grammens 不同意,我会删除。但如果不同意,那么感谢 Justin 的冷静。)
更新
我刚好得到一个关于如何使用代码的评论,并意识到返回类型有错误。
方法签名被设置为返回一个字符串,但在这种情况下它没有返回任何东西。我改了签名
到 HttpResponse,并将在Getting Response Body of HttpResponse 上将您转至此链接
路径变量是 url,我更新以修复代码中的错误。