废话不说上代码 :
public static string httppostwithjson (String URL)은 예외 {httppost httppost = new httppost (url); closeablehttpclient client = httpclients.createdefault (); 문자열 respcontent = null; // json 方式 jsonobject jsonparam = new jsonobject (); jsonparam.put ( "이름", "admin"); jsonparam.put ( "Pass", "123456"); 엄격한 엔티티 = 새로운 엄격함 (jsonparam.tostring (), "utf-8"); // 解决中文乱码问题 entity.setContEncoding ( "UTF-8"); Entity.SetContentType ( "Application/JSON"); httppost.setentity (엔티티); 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 (airlist, "utf-8"); httpresponse resp = client.execute (httppost); if (resp.getStatusline (). getStatuscode () == 200) {httpentity he = resp.getentity (); respcontent = entityutils.toString ( "UTF-8"); } retopcontent 리턴; } public static void main (string [] args)은 예외를 던졌습니다 {문자열 result = httppostwithjson ( "http : // localhost : 8080/hctest2/hc"); System.out.println (결과); }게시물 和 和 이름 方式 方式 패스 就是表单的值了。
封装表单属性可以用 json 也可以用传统的表单 也可以用传统的表单, 如果是传统表单的话 要注意 要注意 要注意 要注意 要注意 要注意 里也就是数据处理层可以通过 里也就是数据处理层可以通过 request.getParameter ( "String") 直接获取到属性值。就是相比 json 这种要简单一点 这种要简单一点 这种要简单一点 这种要简单一点 做数据传输的。用 json 的话有两种选择一个是阿里巴巴的 json 的话有两种选择一个是阿里巴巴的 json 的话有两种选择一个是阿里巴巴的 hastjson 还有一个就是谷歌的 gson。astjson 相比效率比较高 相比效率比较高, gson 适合解析有规律的 json 数据。博主这里用的是 fastjson 。还有用 json 的话在数据处理层要用流来读取表单属性, 这就是相比传统表单多的一点内容。代码下边已经有了。 这就是相比传统表单多的一点内容。代码下边已经有了。
공개 클래스 hcservlet는 httpservlet {private static final long serialversionuid = 1L; 보호 된 void doget (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {dopost (요청, 응답); } 보호 된 void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {request.setcharacterencoding ( "utf-8"); Response.setContentType ( "Text/Html; charset = utf-8"); 문자열 acceptJson = ""; 사용자 user = 새 사용자 (); bufferedReader br = new bufferedReader (new inputStreamReader ((servletInputStream) request.getInputStream (), "UTF-8")); StringBuffer sb = new StringBuffer ( ""); 문자열 온도; 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 ( "사용자", 사용자); request.getRequestDispatcher ( "/message.jsp"). FORMPER (요청, 응답); }}代码比较简陋, 只是用于测试。希望能够有所收获。
以上就是小编为大家带来的 httpclient 模拟 post 请求 json 封装表单数据的实现方法全部内容了, 希望大家多多支持武林网 ~