HTTPClient案例

Posted f017

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTTPClient案例相关的知识,希望对你有一定的参考价值。

依赖

<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax/javaee-api -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
      <scope>provided</scope>
    </dependency>

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<NameValuePair> 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案例的主要内容,如果未能解决你的问题,请参考以下文章

HttpClient“任务被取消”

HTTPClient案例

接口测试HttpClient&fastJson 总结与案例

安卓小案例收集二

07_android入门_採用HttpClient的POST方式GET方式分别实现登陆案例

内部分享:一次HttpClient连接池引发的雪崩案例复盘....