- public static String httpPostWithJSON(String url) throws Exception {
- HttpPost httpPost = new HttpPost(url);
- CloseableHttpClient client = HttpClients.createDefault();
- String respContent = null;
- // json 方式
- JSONObject jsonParam = new JSONObject();
- jsonParam.put("name", "admin");
- jsonParam.put("pass", "123456");
- StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8"); // 解决中文乱码问题
- entity.setContentEncoding("UTF-8");
- entity.setContentType("application/json");
- httpPost.setEntity(entity);
- 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(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);
- }
post 方式 就要考虑提交的表单内容怎么传输了本文 name 和 pass 就是表单的值了
封装表单属性可以用 json 也可以用传统的表单, 如果是传统表单的话 要注意, 也就是在上边代码注释那部分用这种方式的话在 servlet 里也就是数据处理层可以通过 request.getParameter(string) 直接获取到属性值就是相比 json 这种要简单一点, 不过在实际开发中一般都是用 json 做数据传输的用 json 的话有两种选择一个是阿里巴巴的 fastjson 还有一个就是谷歌的 gsonfastjson 相比效率比较高, gson 适合解析有规律的 json 数据博主这里用的是 fastjson 还有用 json 的话在数据处理层要用流来读取表单属性, 这就是相比传统表单多的一点内容代码下边已经有了
- 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);
- }
- }
httpclient 模拟 post 请求 json 封装表单数据
来源: http://www.bubuko.com/infodetail-2491000.html