HTTPClient案例

2021-04-19 19:28

阅读:539

标签:res   created   ticket   https   component   tty   protect   purpose   ebs   

依赖

org.apache.httpcomponents
      httpclient
      4.5.2javax
      javaee-api
      7.0provided

GET

public static void main(String[] args)throws Exception {
        //步骤一:创建一个链接
        CloseableHttpClient client= HttpClients.createDefault();
        //创建一个请求
        HttpGet httpGet=new HttpGet("https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=2020-02-05&leftTicketDTO.from_station=BJP&leftTicketDTO.to_station=SHH&purpose_codes=ADU");
        //执行请求获取节国
        CloseableHttpResponse response=client.execute(httpGet);
        //获取相应的状态码
        System.out.println("服务器返回的状态码:"+response.getStatusLine().getStatusCode());
        if(response.getStatusLine().getStatusCode()==200){
            System.out.println(EntityUtils.toString(response.getEntity(),"UTF-8"));
        }
        //关闭资源
        response.close();
        client.close();
    }

POST

public static void main(String[] args) throws Exception{
        //步骤一:创建一个链接
        CloseableHttpClient client= HttpClients.createDefault();
        //创建请求
        HttpPost post=new HttpPost("http://localhost:8080/post");
        //创建参数队列
        List pairList=new ArrayList();
        pairList.add(new BasicNameValuePair("uname","程"));
        //创建请求体,封装参数
        UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairList,"UTF-8");
        //将请求体交给当前请求
        post.setEntity(entity);

        //发送请求,接收结果
        CloseableHttpResponse response = client.execute(post);
        System.out.println("接收到的结果为:"+ EntityUtils.toString(response.getEntity(),"UTF-8"));


        //关闭资源
        response.close();
        client.close();

    }

Servlet

    @WebServlet("/post")
    public class postServlet extends HttpServlet {
    
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String uname = req.getParameter("uname");
            System.out.println("接收到的值"+uname);
            resp.setContentType("text/html");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write("成功");
        }
    }

 

HTTPClient案例

标签:res   created   ticket   https   component   tty   protect   purpose   ebs   

原文地址:https://www.cnblogs.com/F017/p/12266136.html


评论


亲,登录后才可以留言!