httpclient simulates post request json to encapsulate form data

Source: http://www.cnblogs.com/Vdiao/p/5339487.html
Comments:
I haven't blogged for a long time, and there is no good ink in my stomach, haha. Don't talk nonsense on the code.

Copy code
1 public static String httpPostWithJSON(String url) throws Exception {
2
3 HttpPost httpPost = new HttpPost(url);
4 CloseableHttpClient client = HttpClients.createDefault();
5 String respContent = null;
6        
7 // json method
8 JSONObject jsonParam = new JSONObject(); 
9 jsonParam.put("name", "admin");
10 jsonParam.put("pass", "123456");
11 StringEntity entity = new StringEntity(jsonParam.toString(),"utf- 8");//Solve the problem of Chinese garbled characters   
12         entity.setContentEncoding("UTF-8");   
13         entity.setContentType("application/json");   
14         httpPost.setEntity(entity);
15         System.out.println();
16        
17    
18 //        表单方式
19 //        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
20 //        pairList.add(new BasicNameValuePair("name", "admin"));
21 //        pairList.add(new BasicNameValuePair("pass", "123456"));
22 //        httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));  
23        
24        
25         HttpResponse resp = client.execute(httpPost);
26 if(resp.getStatusLine().getStatusCode() == 200) {
27 HttpEntity he = resp.getEntity();
28 respContent = EntityUtils.toString(he,"UTF-8");
29 }
30 return respContent;
31 }
32
33    
34 public static void main(String[] args) throws Exception {
35 String result = httpPostWithJSON("http://localhost:8080/hcTest2/Hc");
36 System.out.println(result);
37 }
Copy code
post method should consider how the submitted form content is transmitted. In this article, name and pass are the values ​​of the form.

Encapsulated form attributes can use json or traditional forms. If it is a traditional form, pay attention, that is, comment the part of the code above. In this way, in the servlet, that is, the data processing layer, the attribute value can be directly obtained through request.getParameter("string"). It is simpler than json, but in actual development, json is generally used for data transmission. There are two options for using json, one is Alibaba's fastjson and the other is Google's gson. Compared with fastjson, it is more efficient, and gson is suitable for parsing regular JSON data. The blogger uses fastjson here. In addition, if you use json, you need to use stream to read form attributes in the data processing layer, which is a little more content than traditional forms. The code is already there.



Copy code
1 public class HcServlet extends HttpServlet {
2 private static final long serialVersionUID = 1L;
3       
4 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
5 doPost(request, response);
6 }
7
8    
9     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
10        
11         request.setCharacterEncoding("UTF-8"); 
12         response.setContentType("text/html;charset=UTF-8"); 
13         String acceptjson = ""; 
14         User user = new User();
15         BufferedReader br = new BufferedReader(new InputStreamReader( 
16                 (ServletInputStream) request.getInputStream(), "utf-8")); 
17         StringBuffer sb = new StringBuffer(""); 
18         String temp; 
19         while ((temp = br.readLine()) != null) { 
20             sb.append(temp); 
21         } 
22 br.close(); 
23 acceptjson = sb.toString(); 
24 if (acceptjson != "") { 
25 JSONObject jo = JSONObject.parseObject(acceptjson);
26 user.setUsername(jo.getString("name") );
27 user.setPassword(jo.getString("pass"));
28 } 
29        
30 request.setAttribute("user", user);
31 request.getRequestDispatcher("/message.jsp").forward(request, response );
32 }
33 }
Copy code The
code is relatively simple, just for testing. Hope to gain something.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326677300&siteId=291194637