httpClient练习笔记

依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>

代码

public class HttpClientDemo {

    public static void main(String[] args) throws Exception {
//        //get无参数请求
//        httpGetNoParam();
//        //get带参数请求
//        httpGetParam();
//        //post无参数请求
//        httpPostNoParam();
//        //post带参请求
//        httpPostParam();
        //下载图片
        downloadPic("http://img10.360buyimg.com/n1/s450x450_jfs/t1/142896/38/7512/97310/5f5073c9E627505f2/201f731895155325.jpg");
    }
    /**
     * httpclient带参post请求
     */
    public static void httpPostParam() throws Exception {
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //发起get请求创建HttpGet对象
        HttpPost httpPost = new HttpPost("http://www.itcast.cn");
        //请求配置信息
        RequestConfig requestConfig = getRequestConfig();
        //给请求设置请求信息
        httpPost.setConfig(requestConfig);
        //申明List集合,封装表单中的参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //设置参数
        params.add(new BasicNameValuePair("keys","Java"));
        //创建表单entity对象,第一个参数就是封装好的表单数据,第二个参数就是编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"utf8");
        //设置表单的entity对象到post请求中
        httpPost.setEntity(formEntity);
        //使用httpclient对象发起请求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            //4获取数据
            //判断状态码是否是200
            if(response.getStatusLine().getStatusCode()==200){
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                if(httpClient!=null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * httpclient无参post请求
     */
    public static void httpPostNoParam(){
        //1.打开浏览器,创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.输入网址,发起get请求创建HttpGet对象
        HttpPost httpPost = new HttpPost("http://www.itcast.cn");
        //请求配置信息
        RequestConfig requestConfig = getRequestConfig();
        //给请求设置请求信息
        httpPost.setConfig(requestConfig);
        //3.按回车,发起请求,返回响应,使用httpclient对象发起请求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            //4.解析响应,获取数据
            //判断状态码是否是200
            if(response.getStatusLine().getStatusCode()==200){
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                if(httpClient!=null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * httpclient带参get请求
     */
    public static void httpGetParam() throws URISyntaxException {
        //1.打开浏览器,创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求地址是:http://yun.itheima.com/search?keys=Java
        //创建URLBuilder
        URIBuilder uriBuilder = new URIBuilder("http://yun.itheima.com/search");
        //设置参数
        uriBuilder.setParameter("keys","Java");
        //2.输入网址,发起get请求创建HttpGet对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        //请求配置信息
        RequestConfig requestConfig = getRequestConfig();
        //给请求设置请求信息
        httpGet.setConfig(requestConfig);
//        System.out.println(httpGet);
        //3.按回车,发起请求,返回响应,使用httpclient对象发起请求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            //4.解析响应,获取数据
            //判断状态码是否是200
            if(response.getStatusLine().getStatusCode()==200){
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                if(httpClient!=null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * httpclient无参get请求
     */
    public static void httpGetNoParam(){
        //1.打开浏览器,创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.输入网址,发起get请求创建HttpGet对象
        HttpGet httpGet = new HttpGet("http://www.itcast.cn");
        //请求配置信息
        RequestConfig requestConfig = getRequestConfig();
        //给请求设置请求信息
        httpGet.setConfig(requestConfig);
        //3.按回车,发起请求,返回响应,使用httpclient对象发起请求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            //4.解析响应,获取数据
            //判断状态码是否是200
            if(response.getStatusLine().getStatusCode()==200){
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                if(httpClient!=null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下载图片
     * @param imgUrl 图片链接
     */
    public static void downloadPic(String imgUrl){
        //打开浏览器,创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //输入网址,发起get请求创建HttpGet对象
        HttpGet httpGet = new HttpGet(imgUrl);
        //请求配置信息
        RequestConfig requestConfig = getRequestConfig();
        //给请求设置请求信息
        httpGet.setConfig(requestConfig);
        //按回车,发起请求,返回响应,使用httpclient对象发起请求
        CloseableHttpResponse response = null;
        OutputStream outputStream = null;
        try {
            response = httpClient.execute(httpGet);
            if(response!=null){
                //解析响应,获取数据
                //判断状态码是否是200
                if(response.getStatusLine().getStatusCode()==200){
                    //获取图片的后缀名
                    String imgLastName = imgUrl.substring(imgUrl.lastIndexOf("."));
                    //创建图片名
                    String picName = UUID.randomUUID().toString();
                     outputStream = new FileOutputStream(new File("C:\\Users\\yangdong\\Desktop\\images\\"+picName+imgLastName));
                    //下载图片
                    response.getEntity().writeTo(outputStream);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                if(httpClient!=null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 请求配置信息
     * @return
     */
    public static RequestConfig getRequestConfig(){
        //请求配置信息
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000)    //创建连接的最长时间,单位毫秒
                .setConnectionRequestTimeout(500)   //设置获取连接的最长时间,单位是毫秒
                .setSocketTimeout(10*1000)      //设置数据传输的最长时间,单位是毫秒
                .build();
        return requestConfig;
    }
}
http工具类:package com.tpl.util; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; /** * */ public class HttpClientUtil { public static void main(String arg[]) throws Exception { String url = "http://xxx/project/getxxx.action"; JSONObject params= new JSONObject(); List res=new ArrayList(); JSONObject params1 = new JSONObject(); // params1.put("code", "200"); // params1.put("phone", "13240186028"); res.add(params1); params.put("result", res); String ret = doPost(url, params).toString(); System.out.println(ret); } /** httpClient的get请求方式2 * @return * @throws Exception */ public static String doGet(String url, String charset) throws Exception { /* * 使用 GetMethod 来访问一个 URL 对应的网页,实现步骤: 1:生成一个 HttpClinet 对象并设置相应的参数。 * 2:生成一个 GetMethod 对象并设置响应的参数。 3:用 HttpClinet 生成的对象来执行 GetMethod 生成的Get * 方法。 4:处理响应状态码。 5:若响应正常,处理 HTTP 响应内容。 6:释放连接。 */ /* 1 生成 HttpClinet 对象并设置参数 */ HttpClient httpClient = new HttpClient(); // 设置 Http 连接超时为5秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); /* 2 生成 GetMethod 对象并设置参数 */ GetMethod getMethod = new GetMethod(url); // 设置 get 请求超时为 5 秒
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值