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

小编典典

关于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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值