废话不说上代码 :
public static String httppostWithjson (String url) löst eine Ausnahme aus {httppost httppost = new httppost (url); CloseableHttpclient Client = httpclients.CreateFault (); String respcontent = null; // json 方式 jsonObject jsonParam = new JsonObject (); jsonparam.put ("name", "admin"); jsonparam.put ("pass", "123456"); StrackEntity entity = new strackentity (jsonparam.toString (), "utf-8"); // 解决中文乱码问题 entity.setContentCoding ("utf-8"); entity.setContentType ("application/json"); httppost.setentity (Entity); System.out.println (); // 表单方式 // list <BasicNamevaluePair> PARAPLIST = New ArrayList <BasicNamevaluePair> (); // pairlist.add (new BasicNamevaluePair ("Name", "admin"); // pepledlist.add (new BasicNamevaluePair ("Pass", "123456")); // httppost.setentity (neue UrlencodedFormentity (PairList, utf-8 "); HttPresponse resp = client.execute (httppost); if (resp.getStatusline (). getStatusCode () == 200) {httpentity He = resp.getEntity (); respcontent = entityutils.tostring (er, "utf-8"); } return respcontent; } public static void main (String [] args) löst Ausnahme aus {String result = httppostwithjson ("http: // localhost: 8080/hcTest2/hc"); System.out.println (Ergebnis); }Post 方式 就要考虑提交的表单内容怎么传输了。本文 Name 和 Pass 就是表单的值了。
封装表单属性可以用 json 也可以用传统的表单 , 如果是传统表单的话 要注意 , 也就是在上边代码注释那部分。用这种方式的话在 servlet 里也就是数据处理层可以通过 request.getParameter ("String") 直接获取到属性值。就是相比 json 这种要简单一点 不过在实际开发中一般都是用 不过在实际开发中一般都是用 json 做数据传输的。用 json 的话有两种选择一个是阿里巴巴的 fastjson 还有一个就是谷歌的 gson。fastjson 相比效率比较高 , gson 适合解析有规律的 json 数据。博主这里用的是 fastjson 。还有用 json 的话在数据处理层要用流来读取表单属性 , 这就是相比传统表单多的一点内容。代码下边已经有了。 这就是相比传统表单多的一点内容。代码下边已经有了。 这就是相比传统表单多的一点内容。代码下边已经有了。 , gson
public class hcServlet erweitert HttpServlet {private statische endgültige long serialversionuid = 1l; Protected void dodget (httpServletRequest -Anforderung, httpServletResponse -Antwort) löst ServletException aus, ioException {Dopost (Request, Antwort); } Protected void dopost (httpServletRequest-Anforderung, httpServletResponse-Antwort) löst ServletException aus, ioException {request.setcharactercoding ("utf-8"); Antwort.SetContentType ("text/html; charSet = utf-8"); String AcceptJson = ""; User user = new user (); BufferedReader BR = New BufferedReader (neuer InputStreamReader ((ServletInputStream) request.getInputStream (), "utf-8"); StringBuffer sb = new StringBuffer (""); String -Temperatur; while ((temp = br.readline ())! = null) {sb.append (temp); } br.close (); ACCECTJSON = sb.toString (); if (AcceptJson! user.setUserName (jo.getString ("name")); user.setPassword (jo.getString ("pass")); } request.setAttribute ("user", user); Request.GetRequestDispatcher ("/message.jsp"). Weiterleiten (Anfrage, Antwort); }}代码比较简陋 , 只是用于测试。希望能够有所收获。 只是用于测试。希望能够有所收获。
以上就是小编为大家带来的 httpclient 模拟 post 请求 json 封装表单数据的实现方法全部内容了 , 希望大家多多支持武林网 ~