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

标签 android json post httprequest

我试图弄清楚如何使用 HTTPClient 从 Android POST 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();
    }
 }

最佳答案

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

如果您不熟悉 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,我更新以修复代码中的错误。

关于android - 如何在 Android 中使用 HTTPClient 以 JSON 格式发送 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6218143/

相关文章:

php - 使用 cURL PHP 发布多维数组时出现问题

Android map v2 缩放以显示所有标记

java - 可扩展 ListView - child ,不同的布局

json - 使用 JSON 通过 GET 搜索 ElasticSearch

json - UnmarshalText 和 UnmarshalJson 有什么区别?

python - 带分页的 Django API 列表 - 页面不是 JSON 可序列化的

php - Javascript 提交不发送 POST 到 php 文件

android - 何时使用 volley 发送 post 请求

android - 早于 4.2 的 android 中从右到左的元素方向

android - Facebook 登录在发布应用程序之前使用发布 APK,但在发布相同的 APK 之后就不行了