废话不说上代码
public static string httppostwithjson (string url) lança Exceção {httppost httppost = new httppost (url); ClientHttpClient client = httpclients.createFault (); String respcontent = null; // json 方式 jsonObject jsonparam = new jsonObject (); jsonparam.put ("nome", "admin"); jsonparam.put ("passa", "123456"); Stringentity entity = new stringentity (jsonparam.toString (), "utf-8"); // 解决中文乱码问题 entity.setContentEncoding ("utf-8"); entity.setContentType ("Application/json"); httppost.setentity (entidade); System.out.println (); // 表单方式 // List <SicNameValuepair> parList = new ArrayList <SquutNameValuepair> (); // parList.add (new BasicNameValuepair ("Nome", "Admin")); // parList.add (new BasicNameValuepair ("Pass", "123456")); // httppost.setentity (novo UrlencodedFormentity (parlist, "utf-8"); HttpResponse resp = client.execute (httppost); if (resp.getStatusline (). getStatuscode () == 200) {httPentity ele = resp.getEntity (); Respontent = entityutils.toString (He, "UTF-8"); } retornar respontent; } public static void main (string [] args) lança Exceção {string resultado = httppostwithjson ("http: // localhost: 8080/hctest2/hc"); System.out.println (resultado); }Post 方式 就要考虑提交的表单内容怎么传输了。本文 Nome 和 Passe 就是表单的值了。
封装表单属性可以用 JSON 也可以用传统的表单 , 如果是传统表单的话 要注意 , 也就是在上边代码注释那部分。用这种方式的话在 servlet 里也就是数据处理层可以通过 request.getParameter (”String“) 直接获取到属性值。就是相比 JSON 这种要简单一点 , JSON 做数据传输的。用 JSON 的话有两种选择一个是阿里巴巴的 FASTJSON 还有一个就是谷歌的 GSON。FASTJSON 相比效率比较高 , GSON 适合解析有规律的 JSON 数据。博主这里用的是 FASTJSON 。还有用 JSON 的话在数据处理层要用流来读取表单属性 , , , ,
classe pública HCServlet estende httpServlet {private estático final serialversionuid = 1L; Void protegido Doget (solicitação httpServletRequest, httpServletResponse Response) lança servletexception, ioexception {DoPost (solicitação, resposta); } Void protegido doPost (solicitação httpServletRequest, resposta httpServletResponse) lança servletexception, ioexception {request.setcharacterencoding ("utf-8"); Response.setContentType ("Texto/html; charset = utf-8"); String aceitjson = ""; Usuário do usuário = novo usuário (); BUBLEREDRADER BR = new BufferredReader (new InputStreamReader ((ServletInputStream) request.getInputStream (), "utf-8")); StringBuffer sb = new StringBuffer (""); Temp de string; while ((temp = br.readline ())! = null) {sb.append (temp); } Br.Close (); aceitjson = sb.toString (); if (aceitjson! = "") {jsonObject jo = jsonObject.parseObject (aceitjson); user.setUserName (jo.getString ("nome")); user.setPassword (jo.getString ("pass")); } request.setAttribute ("usuário", usuário); request.getRequestDispatcher ("/message.jsp"). Forward (solicitação, resposta); }}代码比较简陋 , 只是用于测试。希望能够有所收获。
以上就是小编为大家带来的 HttpClient 模拟 Post 请求 JSON 封装表单数据的实现方法全部内容了 , 希望大家多多支持武林网 ~