在这个答案中,我使用Justin Grammens发布的示例。
关于JSON
JSON代表Javascript对象符号。在Javascript中,可以像这样
object1.name和这样
引用属性
object['name'];。本文中的示例使用了这部分JSON。
零件
A风扇对象,电子邮件为键,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参考。简而言之,地图类似于字典或哈希。
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)不赞成,我将表示反对。但是如果没有,我要感谢贾斯汀对此的冷静。
更新资料
我刚巧对如何使用代码发表评论,并意识到返回类型有误。方法签名设置为返回字符串,但在这种情况下,它未返回任何内容。我将签名更改为HttpResponse,并将引导您访问HttpResponse
的获取响应正文上的此链接,路径变量为url,并且我进行了更新以修复代码中的错误。



