如何在Android中使用HTTPClient发送JSON格式的POST请求?

2024-03-08

我试图弄清楚如何使用 HTTPClient 从 Android 发布 JSON。我已经尝试解决这个问题有一段时间了,我在网上找到了很多例子,但我无法让它们中的任何一个工作。我相信这是因为我缺乏 JSON/网络知识。我知道那里有很多例子,但有人能给我指出一个实际的教程吗?我正在寻找一个逐步的过程,其中包含代码以及解释为什么要执行每个步骤或该步骤的作用。不需要很复杂,简单就足够了。

再说一次,我知道那里有很多例子,我只是在寻找一个例子来解释到底发生了什么以及为什么会这样做。

如果有人知道一本关于这方面的优秀 Android 书籍,请告诉我。

再次感谢@terrance的帮助,这是我在下面描述的代码

public void shNameVerParams() throws Exception{
     String path = //removed
     HashMap  params = new HashMap();

     params.put(new String("Name"), "Value"); 
     params.put(new String("Name"), "Value");

     try {
        HttpClient.SendHttpPost(path, params);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 }

在这个答案中我使用的是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;
}

请随意评论关于这篇文章出现的任何问题,或者如果我没有说清楚,或者如果我没有触及你仍然困惑的事情......等等,无论你脑子里真正出现什么。

(如果贾斯汀·格拉门斯不同意,我会删除。但如果不同意,那么感谢贾斯汀对此保持冷静。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Android中使用HTTPClient发送JSON格式的POST请求? 的相关文章

随机推荐