httpclient模拟post请求json封装表单数据的实现方法
程序员文章站
2024-03-09 14:41:23
废话不说上代码:
public static string httppostwithjson(string url) throws exception {...
废话不说上代码:
public static string httppostwithjson(string url) throws exception { httppost httppost = new httppost(url); closeablehttpclient client = httpclients.createdefault(); string respcontent = null; // json方式 jsonobject jsonparam = new jsonobject(); jsonparam.put("name", "admin"); jsonparam.put("pass", "123456"); stringentity entity = new stringentity(jsonparam.tostring(),"utf-8");//解决中文乱码问题 entity.setcontentencoding("utf-8"); entity.setcontenttype("application/json"); httppost.setentity(entity); system.out.println(); // 表单方式 // list<basicnamevaluepair> pairlist = new arraylist<basicnamevaluepair>(); // pairlist.add(new basicnamevaluepair("name", "admin")); // pairlist.add(new basicnamevaluepair("pass", "123456")); // httppost.setentity(new urlencodedformentity(pairlist, "utf-8")); httpresponse resp = client.execute(httppost); if(resp.getstatusline().getstatuscode() == 200) { httpentity he = resp.getentity(); respcontent = entityutils.tostring(he,"utf-8"); } return respcontent; } public static void main(string[] args) throws exception { string result = httppostwithjson("http://localhost:8080/hctest2/hc"); system.out.println(result); }
post方式 就要考虑提交的表单内容怎么传输了。本文name和pass就是表单的值了。
封装表单属性可以用json也可以用传统的表单,如果是传统表单的话 要注意,也就是在上边代码注释那部分。用这种方式的话在servlet里也就是数据处理层可以通过request.getparameter(”string“)直接获取到属性值。就是相比json这种要简单一点,不过在实际开发中一般都是用json做数据传输的。用json的话有两种选择一个是阿里巴巴的fastjson还有一个就是谷歌的gson。fastjson相比效率比较高,gson适合解析有规律的json数据。博主这里用的是fastjson。还有用json的话在数据处理层要用流来读取表单属性,这就是相比传统表单多的一点内容。代码下边已经有了。
public class hcservlet extends httpservlet { private static final long serialversionuid = 1l; protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { dopost(request, response); } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { request.setcharacterencoding("utf-8"); response.setcontenttype("text/html;charset=utf-8"); string acceptjson = ""; user user = new user(); bufferedreader br = new bufferedreader(new inputstreamreader( (servletinputstream) request.getinputstream(), "utf-8")); stringbuffer sb = new stringbuffer(""); string temp; while ((temp = br.readline()) != null) { sb.append(temp); } br.close(); acceptjson = sb.tostring(); if (acceptjson != "") { jsonobject jo = jsonobject.parseobject(acceptjson); user.setusername(jo.getstring("name")); user.setpassword(jo.getstring("pass")); } request.setattribute("user", user); request.getrequestdispatcher("/message.jsp").forward(request, response); } }
代码比较简陋,只是用于测试。希望能够有所收获。
以上就是小编为大家带来的httpclient模拟post请求json封装表单数据的实现方法全部内容了,希望大家多多支持~
下一篇: asp.net Web站点风格切换的实现