1. 程式人生 > >httpclient模擬post請求json封裝表單數據

httpclient模擬post請求json封裝表單數據

readline turn ast acc [] 選擇 encoding 效率 set

 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方式
 8         JSONObject jsonParam = new JSONObject();  
 9         jsonParam.put("name", "admin");
10         jsonParam.put("pass", "123456");
11         StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解決中文亂碼問題    
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     }

post方式 就要考慮提交的表單內容怎麽傳輸了。本文name和pass就是表單的值了。

封裝表單屬性可以用json也可以用傳統的表單,如果是傳統表單的話 要註意,也就是在上邊代碼註釋那部分。用這種方式的話在servlet裏也就是數據處理層可以通過request.getParameter(”string“)直接獲取到屬性值。就是相比json這種要簡單一點,不過在實際開發中一般都是用json做數據傳輸的。用json的話有兩種選擇一個是阿裏巴巴的fastjson還有一個就是谷歌的gson。fastjson相比效率比較高,gson適合解析有規律的json數據。博主這裏用的是fastjson。還有用json的話在數據處理層要用流來讀取表單屬性,這就是相比傳統表單多的一點內容。代碼下邊已經有了。

 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 }

httpclient模擬post請求json封裝表單數據