一、urlencodedformentity
//设置请求方式与参数
uri uri = new uri(uristr);
httppost httppost = new httppost(uri);
httppost.getparams().setparameter("http.socket.timeout", new integer(500000));
httppost.setheader("content-type", "text/plain; charset=utf-8");
httppost.setheader("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows 2000)");
httppost.setheader("iconnection", "close");
list<namevaluepair> nvps = new arraylist<namevaluepair>();
nvps.add(new basicnamevaluepair("key1", "value1"));
//...
httppost.setentity(new urlencodedformentity(nvps));
//执行请求
httpclient httpclient = new defaulthttpclient();
httpclient.getparams().setparameter("content-encoding", "utf-8");
httpresponse response = httpclient.execute(httppost);
//获取返回
httpentity entity = response.getentity();
bufferedreader in = new bufferedreader(new inputstreamreader(entity.getcontent(), "utf-8"));
stringbuffer buffer = new stringbuffer();
string line = null;
while ((line = in.readline()) != null) {
buffer.append(line);
}
return buffer.tostring();
使用 urlencodedformentity 来设置 body,消息体内容类似于“key1=value1&key2=value2&…”这种形式,服务端接收以后也要依据这种协议形式做处理。
二、stringentity
有时候我们不想使用上述格式来传值,而是想使用json格式来设置body,就可以使用这个类的实例。
jsonobject jsonobject = new jsonobject();
jsonobject.put("key1", "value1");
jsonobject.put("key2", "value2");
httppost.setentity(new stringentity(jsonobject.tostring()));
可以看出,urlencodedformentity()的形式比较单一,只能是普通的键值对,局限性相对较大。
而stringentity()的形式比较自由,只要是字符串放进去,不论格式都可以。
httpclient发送post请求:stringentity 和 urlencodedformentity
一. json简介
json是一种取代xml的数据结构,和xml相比,它更小巧但描述能力却不差,由于它的小巧所以网络传输数据将减少更多流量从而加快速度。
json就是一串字符串 只不过元素会使用特定的符号标注。
a. {} 双括号表示对象
b. [] 中括号表示数组
c. “” 双引号内是属性或值
d. : 冒号表示后者是前者的值(这个值可以是字符串、数字、也可以是另一个数组或对象)
所以 {“name”: “michael”} 可以理解为是一个包含name为michael的对象。而[{“name”: “michael”},{“name”: “jerry”}]就表示包含两个对象的数组。当然了,可以使用{“name”:[“michael”,“jerry”]}来简化,这是一个拥有一个name数组的对象。
json格式数据的优点:
a.数据格式比较简单,易于读写,格式都是压缩的,占用带宽小,是非常轻量级的数据格式;
b.易于解析,客户端javascript可以简单的通过eval()进行json数据的读取;
c.支持多种语言,其中在java端有丰富的工具操作和解析json;
d.因为json格式能直接为服务器端代码使用,大大简化了服务器端和客户端的代码开发量,且完成任务不变,并且易于维护;
二. jsonobject 、jsonarray
1,jsonobject
json对象,就是一个键对应一个值,使用的是大括号{ },如:{key:value}
2,jsonarray
json数组,使用中括号[ ],只不过数组里面的项也是json键值对格式的json对象中添加的是键值对,jsonarray中添加的是json对象
jsonobject json = new jsonobject(); jsonarray jsonarray = new jsonarray(); json.put(“key”, “value”);//jsonobject对象中添加键值对 jsonarray.add(json);//将jsonobject对象添加到json数组中
3,jsonobject与map
map map和json都是键值对,不同的是map中键值对中间用等号分开,json中键值对中间用冒号分开。json就是一种特殊形式的map。
map<string,string> strmap=new jsonobject();
这里的需求是:request对象获取的map,想要返回json格式也不用白费力了。
[{name1:{name2:{name3:‘value1',name4:‘value2'}}},{}]
取出name4值过程步骤:
1,将以上字符串转换为jsonarray对象;
2,取出对象的第一项,jsonobject对象;
3,取出name1的值jsonobject对象;
4,取出name2的值jsonobject对象;
5,取出name4的值value2。
示例中json数组格式的字符串可以通过方法直接转换为jsonarray的格式:
jsonarray.fromobject(string) jsonarray getjsonarray=jsonarray.fromobject(arraystr);//将结果转换成jsonarray对象的形式 jsonobject getjsonobj = getjsonarray.getjsonobject(0);//获取json数组中的第一项 string result=getjsonobj.getjsonobject(“name1”).getjsonobject(“name2”).getjsonobject(“name4”);
三. json解析
1.传统的json解析
1、生成json字符串
public static string createjsonstring(string key, object value) {
jsonobject jsonobject = new jsonobject();
jsonobject.put(key, value);
return jsonobject.tostring();
}
2、解析json字符串:分为以下三种情况,一个javabean,一个list数组,一个嵌套map的list数组
//完成对json数据的解析
public class jsontools {
public static person getperson(string key, string jsonstring) {
person person = new person();
try {
jsonobject jsonobject = new jsonobject(jsonstring);
jsonobject personobject = jsonobject.getjsonobject("person");
person.setid(personobject.getint("id"));
person.setname(personobject.getstring("name"));
person.setaddress(personobject.getstring("address"));
} catch (exception e) {
// todo: handle exception
}
return person;
}
public static list getpersons(string key, string jsonstring) {
list list = new arraylist();
try {
jsonobject jsonobject = new jsonobject(jsonstring);
// 返回json的数组
jsonarray jsonarray = jsonobject.getjsonarray(key);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject jsonobject2 = jsonarray.getjsonobject(i);
person person = new person();
person.setid(jsonobject2.getint("id"));
person.setname(jsonobject2.getstring("name"));
person.setaddress(jsonobject2.getstring("address"));
list.add(person);
}
} catch (exception e) {
// todo: handle exception
}
return list;
}
public static list getlist(string key, string jsonstring) {
list list = new arraylist();
try {
jsonobject jsonobject = new jsonobject(jsonstring);
jsonarray jsonarray = jsonobject.getjsonarray(key);
for (int i = 0; i < jsonarray.length(); i++) {
string msg = jsonarray.getstring(i);
list.add(msg);
}
} catch (exception e) {
// todo: handle exception
}
return list;
}
public static list> listkeymaps(string key,string jsonstring) {
list> list = new arraylist>();
try {
jsonobject jsonobject = new jsonobject(jsonstring);
jsonarray jsonarray = jsonobject.getjsonarray(key);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject jsonobject2 = jsonarray.getjsonobject(i);
map map = new hashmap();
iterator iterator = jsonobject2.keys();
while (iterator.hasnext()) {
string json_key = iterator.next();
object json_value = jsonobject2.get(json_key);
if (json_value == null) {
json_value = "";
}
map.put(json_key, json_value);
}
list.add(map);
}
} catch (exception e) {
// todo: handle exception
}
return list;
}
}
2.json解析之gson
1、生成json字符串
import com.google.gson.gson;
public class jsonutils {
public static string createjsonobject(object obj) {
gson gson = new gson();
string str = gson.tojson(obj);
return str;
}
}
2、解析json
public class gsontools {
public gsontools() {
// todo auto-generated constructor stub
}
/**
* @param
* @param jsonstring
* @param cls
* @return
*/
public static t getperson(string jsonstring, class cls) {
t t = null;
try {
gson gson = new gson();
t = gson.fromjson(jsonstring, cls);
} catch (exception e) {
// todo: handle exception
}
return t;
}
/**
* 使用gson进行解析 list
* @param
* @param jsonstring
* @param cls
* @return
*/
public static list getpersons(string jsonstring, class cls) {
list list = new arraylist();
try {
gson gson = new gson();
list = gson.fromjson(jsonstring, new typetoken>() {
}.gettype());
} catch (exception e) {
}
return list;
}
/**
* @param jsonstring
* @return
*/
public static list getlist(string jsonstring) {
list list = new arraylist();
try {
gson gson = new gson();
list = gson.fromjson(jsonstring, new typetoken>() {
}.gettype());
} catch (exception e) {
// todo: handle exception
}
return list;
}
public static list> listkeymaps(string jsonstring) {
list> list = new arraylist>();
try {
gson gson = new gson();
list = gson.fromjson(jsonstring,
new typetoken>>() {
}.gettype());
} catch (exception e) {
// todo: handle exception
}
return list;
}
}
3.json解析之fastjson
public class jsontool {
public static t getperson(string jsonstring, class cls) {
t t = null;
try {
t = json.parseobject(jsonstring, cls);
} catch (exception e) {
// todo: handle exception
}
return t;
}
public static list getpersonlist(string jsonstring, class cls) {
list list = new arraylist();
try {
list = json.parsearray(jsonstring, cls);
} catch (exception e) {
// todo: handle exception
}
return list;
}
public static list> getpersonlistmap1( string jsonstring) {
list> list = new arraylist>();
try {
list = json.parseobject(jsonstring,
new typereference>>() {
}.gettype());
} catch (exception e) {
// todo: handle exception
}
return list;
}
}
json对于移动设备来说,尤其对于网络环境较差和流量限制的情况下,相对于xml格式的数据传输会更节省流量,传输效率更高。在这三种解析方式中fastjson是效率最高的,推荐使用。
四. httpclient发送post请求:stringentity 和 urlencodedformentity
1.stringentity
stringentity有两个参数,一个是具体的参数值(string串),另一个是contenttype,默认是text/plain,编码格式是:iso_5598_1。
使用httpclient时,尽量指定编码方式来初始化stringentity。
使用httpclient来发送请求获取数据:拼接出来的body本质是一串sring,所以可以用stringentity,使用方法如下:
//构造测试数据
jsonobject param = new jsonobject();
param.put("key","value");
//closeablehttpclient:建立一个可以关闭的httpclient
//这样使得创建出来的http实体,可以被java虚拟机回收掉,不至于出现一直占用资源的情况。
closeablehttpclient client = httpclients.createdefault();
//创建post请求
httppost post = new httppost(testurl);
//生成装载param的entity
stringentity entity = new stringentity(param.tostring(), "utf-8");
post.setentity(entity);
//执行请求
closeablehttpresponse response = testconfig.httpclient.execute(post);
//返回string格式的结果
string result = entityutils.tostring(response.getentity(), "utf-8");
//关闭链接
post.releaseconnection();
client.close();
2.urlencodedformentity
contenttype就是application/x-www-form-urlencoded,urlencodeformentity会将参数以key1=value1&key2=value2的键值对形式发出。类似于传统的application/x-www-form-urlencoded表单上传。
//构造测试数据
list<namevaluepair> param = new arraylist<namevaluepair>();
param.add(new basicnamevaluepair("key1","value1"));
param.add(new basicnamevaluepair("key2","value2"));
//定义httpclient
closeablehttpclient client = httpclients.createdefault();
//创建post请求
httppost post = new httppost(testurl);
//生成装载param的entity
httpentity entity = new urlencodedformentity(param, "utf-8");
post.setentity(entity);
//执行请求
closeablehttpresponse response = client.execute(post);
//返回string格式的结果
string result = entityutils.tostring(response.getentity(), "utf-8");
//关闭链接
post.releaseconnection();
client.close();
stringentity可以用来灵活设定参数格式形式,而urlencodeformentity则适合于传统表单格式的参数形式。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
无耻的马赛克