我试图弄清楚如何使用HTTPClient从Android发布JSON.我想弄明白这一点已经有一段时间了,我在网上找到了很多例子,但我无法让它们中的任何一个发挥作用.我相信这是因为我缺乏JSON/网络知识.我知道有很多例子,但有人能给我指一个实际的教程吗?我正在寻找一个循序渐进的过程,其中包含代码,并解释为什么要执行每个步骤,或者该步骤的功能.不需要复杂,简单就足够了.

再说一次,我知道有一大堆例子,我只是在寻找一个例子,解释到底发生了什么,以及为什么会这样做.

如果有人知道有一本关于这方面的Android好书,那么请让我知道.

Thanks again for the help @terrance, here is the code I described below

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.

About JSON

JSON代表JavaScript对象表示法.在JavaScript中,属性可以像object1.nameobject['name'];这样引用.本文中的示例使用了这一点JSON.

The Parts
A fan object with email as a key and foo@bar.com as a value

{
  fan:
    {
      email : 'foo@bar.com'
    }
}

So the object equivalent would be fan.email; or fan['email'];. Both would have the same value of 'foo@bar.com'.

About HttpClient Request

The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.

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数据 struct ,请查看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;
}

Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.

(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)

更新

I just happend to get a comment about how to use the code and realized that there was a mistake in the return type. The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse the path variable is the url and I updated to fix a mistake in the code.

Json相关问答推荐

JSON字符串处理注入引号

为什么JQ筛选器不将原始输入打印为$var|.';文档?

Bash和echo命令出现意外结果

由于无效的UTF-8开始字节0xa0,JSON被拒绝,但编码似乎有效

数据到jsonObject到数据到 struct 是可能的吗?

XSLT 3.0 Json-to-xml,json 包含 html struct

如何使用jolt将嵌套数据变成线性数据

如何使用 jq 在连续的 json 记录流上调用操作

将请求中的数据推送到数组中

如何从 JSON 中获取数据并通过 vb6 在网格中显示

如何将从嵌套 Select 返回的空值转换为空数组?

hook到 Decodable.init() 以获得未指定的键?

Jolt - 在同一级别添加时组合值的问题

使用 JSON 的 javascript 深拷贝

使用 JSONObject 在 Java 中为以下 struct 创建嵌套 JSON 对象?

jQuery.getJSON 和 jQuery.parseJSON 返回 [object Object]?

使用 Retrofit 解析动态密钥 Json 字符串

Gson 将一组数据对象转换为 json - Android

PHP json_encode json_decode UTF-8

C++:使用 nlohmann json 从文件中读取 json 对象