httpclient simulates how post requests json to encapsulate form data

  • 2020-05-26 08:36:52
  • OfStack

Don't talk nonsense on the code:


public static String httpPostWithJSON(String url) throws Exception {

    HttpPost httpPost = new HttpPost(url);
    CloseableHttpClient client = HttpClients.createDefault();
    String respContent = null;
    
//    json way 
    JSONObject jsonParam = new JSONObject(); 
    jsonParam.put("name", "admin");
    jsonParam.put("pass", "123456");
    StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");// Solve the problem of Chinese garbled code   
    entity.setContentEncoding("UTF-8");  
    entity.setContentType("application/json");  
    httpPost.setEntity(entity);
    System.out.println();
    
  
//     The form way 
//    List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); 
//    pairList.add(new BasicNameValuePair("name", "admin"));
//    pairList.add(new BasicNameValuePair("pass", "123456"));
//    httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));  
    
    
    HttpResponse resp = client.execute(httpPost);
    if(resp.getStatusLine().getStatusCode() == 200) {
      HttpEntity he = resp.getEntity();
      respContent = EntityUtils.toString(he,"UTF-8");
    }
    return respContent;
  }

  
  public static void main(String[] args) throws Exception {
    String result = httpPostWithJSON("http://localhost:8080/hcTest2/Hc");
    System.out.println(result);
  }

The post approach takes into account how the content of the submitted form is transmitted. For this article, name and pass are the values of the form.

Encapsulating form properties can be done with json or with a traditional form, which you should note if it's a traditional form, as in the code comments section above. In this way, the data processing layer in servlet can get the property values directly through request.getParameter (" string "). It's a little bit simpler than json, but in the real world, json is used for data transfer. There are two choices for json: one is alibaba's fastjson and the other is Google's gson. While fastjson is more efficient, gson is suitable for parsing regular json data. The blogger is using fastjson. Also with json you have to stream in the data processing layer to read the form properties, which is one more point than a traditional form. It's already under the code.


public class HcServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
    
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
  }

  
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    request.setCharacterEncoding("UTF-8"); 
    response.setContentType("text/html;charset=UTF-8"); 
    String acceptjson = ""; 
    User user = new User();
    BufferedReader br = new BufferedReader(new InputStreamReader( 
        (ServletInputStream) request.getInputStream(), "utf-8")); 
    StringBuffer sb = new StringBuffer(""); 
    String temp; 
    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("user", user);
    request.getRequestDispatcher("/message.jsp").forward(request, response);
  }
}

The code is crude, just for testing. I hope I can get some results.


Related articles: