zoukankan      html  css  js  c++  java
  • HttpClient

    * 步骤:
        1. 创建HttpClient对象
        2. 创建HttpGet或者HttpPost对象。将地址传给构造方法。
        3. 让HttpClient对象执行请求。得到响应对象HttpResponse
        4. 从HttpResponse对象中得到响应码。
        5. 判断响应码是否为200,如果200则获得HttpEntity.
        6. 用EntityUtils将数据从HttpEntity中获得

    //http://localhost:8080/MyServer/login?username=admin&userpwd=111
    String path = "http://localhost:8080/MyServer/login";
    //1:创建HttpClient
    HttpClient client = new DefaultHttpClient();
    //2:创建请求。
    HttpPost post = new HttpPost(path);
    //将数据封装到post对象里。
    //创建一个存储封装键值对对象的集合
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    //将数据封装到NameValuePair对象里,第一个参数为键,第二个参数为值
    NameValuePair value1 = new BasicNameValuePair("username", "admin");
    NameValuePair value2 = new BasicNameValuePair("userpwd", "1112");
    //将对象添加到集合中。
    params.add(value1);
    params.add(value2);
    //将数据集合封装成HttpEntity
    HttpEntity entity = new UrlEncodedFormEntity(params);
    //设置HttpEntity
    post.setEntity(entity);
    //让客户端执行请求。
    HttpResponse response = client.execute(post);
    int code = response.getStatusLine().getStatusCode();
    if(code==200){
        HttpEntity result_entity = response.getEntity();
        String str = EntityUtils.toString(result_entity);
        System.out.println(str);
    }
    //创建HttpClient对象--客户端
    HttpClient client = new DefaultHttpClient();
    //创建请求。---Get:HttpGet
    String path = "http://a3.att.hudong.com/36/11/300001378293131694113168235_950.jpg";
    HttpGet get = new HttpGet(path);
    //让客户端执行请求。得到响应对象
    try {
        HttpResponse response = client.execute(get);
        //得到响应码。:响应码和服务器端发送给客户端的数据都封装在HttpResponse里。
        int code = response.getStatusLine().getStatusCode();
        if(code==200){
            //成功响应。
            //得到服务器端的数据。
            HttpEntity entity = response.getEntity();
            byte[] b = EntityUtils.toByteArray(entity);
            //将byte数组的数据写到文件中。
            FileOutputStream fos = new FileOutputStream("f:\a3.jpg");
            fos.write(b);
            fos.close();
        }
  • 相关阅读:
    SpringBoot构建大数据开发框架
    阿里云 docker连接总报超时 registry.cn-hangzhou.aliyuncs.com (Client.Timeout exceeded while awaiting headers
    这些保护Spring Boot 应用的方法,你都用了吗?
    那些年让你迷惑的阻塞、非阻塞、异步、同步
    spring data jpa 分页查询
    如何在Windows 10上运行Docker和Kubernetes?
    Spring Mvc和Spring Boot配置Tomcat支持Https
    Why I don't want use JPA anymore
    Spring Data JPA Batch Insertion
    MySQL 到底能不能放到 Docker 里跑?
  • 原文地址:https://www.cnblogs.com/anni-qianqian/p/5243450.html
Copyright © 2011-2022 走看看