小编典典

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

json

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

阅读 247

收藏
2020-07-27

共1个答案

小编典典

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

关于JSON

JSON代表JavaScript对象符号。在JavaScript中,可以像这样object1.name和这样
引用属性object['name'];。本文中的示例使用了这部分JSON。

零件
A风扇对象,电子邮件为键,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数据结构,请查看Java
Map参考
。简而言之,地图类似于字典或哈希。

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)不赞成,我将表示反对。但是如果没有,我要感谢贾斯汀对此的冷静。

更新资料

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

2020-07-27