且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-19 07:04:54

在此答案中,我使用的是

In this answer I am using an example posted by Justin Grammens.

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

JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.

零件
一个风扇对象,电子邮件为密钥,foo@bar.com为值

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

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

因此对象等效项为fan.email;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'.

以下是我们的作者用来制作的内容HttpClient请求.我并不声称自己是专家,因此,如果有人可以用更好的方式来表达某些术语,那就可以了.

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

If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.

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.

(如果Justin Grammens不赞成,我会拒绝接受.但是如果没有,我要感谢Justin对此很酷.)

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

我刚巧对如何使用代码发表评论,并意识到返回类型有误. 方法签名设置为返回字符串,但在这种情况下,它未返回任何内容.我改变了签名 到HttpResponse的链接,并将在获取响应中将该链接引荐您HttpResponse的正文 path变量是url,我已更新以修复代码中的错误.

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.