且构网

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

如何使用了HTTPClient的JSON发送POST请求?

更新时间:2023-01-17 08:08:50

在这个答案我正在使用的例如张贴者贾斯汀Grammens

关于JSON

JSON代表JavaScript对象符号。在JavaScript性能可以参考这两个这样的 object1.name 像这样对象['名称']; 。从文章的例子使用JSON的该位。

的配件
使用电子邮件作为重点,并foo@bar.com作为一种价值

一个风扇对象
  {
  风扇:
    {
      电子邮件:foo@bar.com
    }
}
 

所以,对象相当于将 fan.email; 风扇[电子邮件]; 。这两个国家都相同的值 对'foo@bar.com

关于HttpClient的请求

下面是我们的作者用来做HttpClient申请。我不敢说是专家,在这一切,所以如果任何人有更好的方式来字的一些术语感到***。

 公共静态的Htt presponse makeRequest(字符串路径,地图PARAMS)抛出异常
{
    // HttpClient的实例,使申请
    DefaultHttpClient的HttpClient =新DefaultHttpClient();

    // URL的POST数据
    HttpPost httpost =新HttpPost(路径);

    //转换参数成JSON对象
    JSONObject的持有人= getJsonObjectFromMap(PARAMS);

    //将结果传递给一个字符串生成器/实体
    StringEntity本身=新StringEntity(holder.toString());

    //设置POST请求的结果字符串
    httpost.setEntity(SE);
    //设置一个请求头以便页面receving请求
    //知道该怎么用它做
    httpost.setHeader(接受,应用/ JSON);
    httpost.setHeader(内容型,应用/ JSON);

    //手柄什么从页返回的
    ResponseHandler的ResponseHandler的=新BasicResponseHandler();
    返回httpclient.execute(httpost,ResponseHandler所);
}
 

地图

如果您不熟悉的地图数据结构,请大家看一下的 Java的地图参考。总之,地图是类似于字典或散列。

 私有静态的JSONObject getJsonObjectFromMap(地图PARAMS)抛出JSONException {

    //所有的POST请求传递的参数
    //迭代通过所有的参数用于循环
    //传入的post请求
    迭代器ITER = params.entrySet()迭代器()。

    //商店JSON
    JSONObject的持有人=新的JSONObject();

    //使用前面的例子你的第一个条目将收到电子邮件
    //和内部同时将获得这将是值foo@bar.com
    // {风扇:{电子邮件:foo@bar.com}}

    //虽然有另一个项目
    而(iter.hasNext())
    {
        //获取在PARAMS一个条目
        Map.Entry对=(Map.Entry的)iter.next();

        //创建一个键地图
        字符串键=(字符串)pairs.getKey();

        //创建一个新的地图
        图M =(图)pairs.getValue();

        //对象存储的Json
        JSONObject的数据=新的JSONObject();

        //获取价值
        。迭代器iter2 = m.entrySet()迭代();
        而(iter2.hasNext())
        {
            Map.Entry的pairs2 =(Map.Entry的)iter2.next();
            data.put((字符串)pairs2.getKey(),(串)pairs2.getValue());
        }

        //把电子邮件和foo@bar.com一起在地图上
        holder.put(键,数据);
    }
    回报持有人;
}
 

请随意发表评论,认为出现这个职位有任何疑问或如果我还没有做出明确的东西,或者如果我没有触及的东西,你仍然感到困惑......等一切在你的脑袋弹出真的。

(我会下来,如果贾斯汀Grammens不批准。但是,如果没有的话感谢贾斯汀为是很酷的。)

更新

我只是happend,以获取有关如何使用code注释并意识到,有在返回类型的错误。 方法签名被设置为返回一个字符串,但在这种情况下,它不是返回任何东西。我改了签名 到Htt的presponse,并会向您推荐此链接的获取的响应体的Htt presponse 路径变量是URL,我更新,以修复在code是错误的。

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 complex, 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 done that way.

If anyone knows of a good Android book that deals with this please let me know.

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

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

About 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.

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

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.

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

Update

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.