如何在 Android 中使用 HTTPClient 以 JSON 格式发送 POST 请求? [英] How to send POST request in JSON using HTTPClient in Android?

查看:41
本文介绍了如何在 Android 中使用 HTTPClient 以 JSON 格式发送 POST 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何使用 HTTPClient 从 Android POST JSON.我一直试图解决这个问题,我在网上找到了很多例子,但我无法让其中任何一个工作.我相信这是因为我缺乏 JSON/网络知识.我知道那里有很多例子,但有人可以指点我一个实际的教程吗?我正在寻找带有代码的分步过程,并解释您为什么要执行每一步,或该步骤的作用.不需要很复杂,简单就够了.

I'm trying to figure out how to POST JSON from Android by using HTTPClient. I've been trying to figure this out for a while, I have found plenty of examples online, but I cannot get any of them to work. I believe this is because of my lack of JSON/networking knowledge in general. I know there are plenty of examples out there but could someone point me to an actual tutorial? I'm looking for a step by step process with code and explanation of why you do each step, or of what that step does. It doesn't need to be a complicated, simple will suffice.

再说一次,我知道有很多例子,我只是在寻找一个例子来解释究竟发生了什么以及为什么会这样.

Again, I know there are a ton of examples out there, I'm just really looking for an example with an explanation of what exactly is happening and why it is doing that way.

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

If someone knows about a good Android book on this, then please let me know.

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

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();
    }
 }

推荐答案

在这个答案中,我使用了一个 Justin Grammens 发布的示例.

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 数据结构,请查看 Java 地图参考.简而言之,地图类似于字典或哈希.

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 并会在 Getting Response 上向您推荐此链接HttpResponse 的主体路径变量是 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.

这篇关于如何在 Android 中使用 HTTPClient 以 JSON 格式发送 POST 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆