HttpClient知识总结

HttpClient知识总结

一.HttpClient简介

HttpClient是一个可以让java应用程序使用http协议访问网络资源的客户端编程工具包。(JDK中java.net包也提供了基本的HTTP访问资源功能,但是不能做复杂处理)

二.HttpClient包

在maven中导入httpClient包(如下),或者在官网中下载jar包手动导入到项目中。

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version> <!-- 请检查是否有更新的版本 -->
</dependency>

三.HttpClient应用

1.Get请求,无参数

 //1.创建一个client对象
        CloseableHttpClient client = HttpClients.createDefault();
 //2.创建Get请求对象,在请求中输入url
        HttpGet get=new HttpGet("http://www.baidu.com");
 //3.发送请求,返回响应数据
        CloseableHttpResponse res = client.execute(get);
 //4.获取响应的状态码
        int code = res.getStatusLine().getStatusCode();
        System.out.println(code);
 //5.处理响应数据
        HttpEntity entity = res.getEntity();
        String content = EntityUtils.toString(entity, "utf-8");
        System.out.println(content);
 //6.关闭链接
        client.close();

2.Get请求,有参数

//1.创建client对象
        CloseableHttpClient client = HttpClients.createDefault();
//2.创建一个封装URI的对象,在该对象中可以给定请求参数
        URIBuilder bui = new URIBuilder("http://www.baidu.com/s");
        bui.addParameter("word","西游记");
//3.创建一个Get请求对象
        HttpGet get = new HttpGet(bui.build());
//4.发送请求对象,并且获得响应数据
        CloseableHttpResponse res = client.execute(get);
//5.获取请求码
        int code = res.getStatusLine().getStatusCode();
        System.out.println("请求码:"+code);
//6.获取响应内容,处理响应数据
        HttpEntity entity = res.getEntity();
        String content = EntityUtils.toString(entity);
        System.out.println(content);
//7.关闭client
        client.close();

3.Post请求,无参数

//1.创建Client对象
        CloseableHttpClient client = HttpClients.createDefault();
//2.创建一个Post对象,在请求中输入url
        HttpPost post = new HttpPost("http://www.baidu.com/");
//3.发送post请求,并获得响应数据
        CloseableHttpResponse res = client.execute(post);
//4.获得响应码
        int code = res.getStatusLine().getStatusCode();
        System.out.println("Post无参数响应码:"+code);
//5.处理响应数据
        HttpEntity entity = res.getEntity();
        String content = EntityUtils.toString(entity, "utf-8");
        System.out.println(content);
//6.关闭client
        client.close();

4.Post请求,有参数

//        1.创建client对象
        CloseableHttpClient client = HttpClients.createDefault();
//        2.创建post对象
        HttpPost post = new HttpPost("https://cn.bing.com/search?");
//        3.设定参数,将参数加入到post对象中
        List<BasicNameValuePair> list=new ArrayList<>();//参数先存入数组中
        list.add(new BasicNameValuePair("q","响应码302"));
        StringEntity entity = new UrlEncodedFormEntity(list, "utf-8");//将参数做字符串的转换
        post.setEntity(entity);//将参数加入到post对象中
//        4.发送请求,获得响应数据
        CloseableHttpResponse res = client.execute(post);
//        5.获得响应码
        int code = res.getStatusLine().getStatusCode();
        System.out.println("post带参数,响应码:"+code);
//        6.处理响应数据
        HttpEntity entity1 = res.getEntity();
        String content = EntityUtils.toString(entity1, "utf-8");
        System.out.println(content);
//        7.关闭client
        client.close();

5.Post请求,带JSON格式参数

//        1.创建client对象
        CloseableHttpClient client = HttpClients.createDefault();
//        2.创建post对象
        HttpPost post = new HttpPost("https://cn.bing.com/search?");
//        3.设置Post传入的JSON字符串参数
        String json="{\"q\":\"响应码302\"}";
        StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
        post.setEntity(entity);
//        4.发送请求,获取响应数据
        CloseableHttpResponse res = client.execute(post);
//        5.返回响应码
        int code = res.getStatusLine().getStatusCode();
        System.out.println("post请求带Json参数:"+code);
//        6.处理响应数据
        HttpEntity entity1 = res.getEntity();
        String content = EntityUtils.toString(entity1, "utf-8");
        System.out.println(content);

6.HttpClient自定义工具类的使用

根据上述内容,我们可以将HttpClient封装成一个工具类HttpClientUtil

6.1编写工具类HttpClient
public class HttpClientUtil {
    //GET请求,带参数
    public static String doGet(String url, Map<String,String>param){
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String resultString="";
        CloseableHttpResponse response=null;
        //创建uri
        try {
            URIBuilder builder = new URIBuilder(url);
            if(param!=null){
                for(String key:param.keySet()){
                    builder.addParameter(key,param.get(key));
                }
            }
            URI uri=builder.build();

//            创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            //执行请求
            response=httpClient.execute(httpGet);
            //判断返回状态是否为200
            if(response.getStatusLine().getStatusCode()==200){
                resultString= EntityUtils.toString(response.getEntity(),"utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response!=null){
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    //GET请求,无参数
    public static String doGet(String url){
        return doGet(url,null);
    }

    //Post请求,带参数
    public static String doPost(String url,Map<String,String> param){
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response=null;
        String resultString="";
            try {
                //创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                //创建参数列表
                if(param!=null){
                    List<NameValuePair> paramList=new ArrayList<>();
                    for(String key:param.keySet()){
                        paramList.add(new BasicNameValuePair(key,param.get(key)));
                    }
                    //模拟表单
                    UrlEncodedFormEntity entity=new UrlEncodedFormEntity(paramList,"utf-8");
                    httpPost.setEntity(entity);
                }
                //执行http请求
                response=httpClient.execute(httpPost);
                resultString=EntityUtils.toString(response.getEntity(),"utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try{
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        return  resultString;
    }

    //Post请求,不带参数
    public static String doPost(String url){
        return doPost(url,null);
    }
    
    //Post请求,带Json参数
    public static String doPostJson(String url,String json){
        //创建client对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response=null;
        String resultString="";
        try {
//            创建http Post请求
            HttpPost httpPost = new HttpPost(url);
            //创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            //执行http请求
            response=httpClient.execute(httpPost);
            resultString=EntityUtils.toString(response.getEntity(),"utf-8");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return resultString;
    }
}

6.2测试工具类HttpClientUitl
 public static void httpClientUtilTest(){
        String url="https://cn.bing.com/search?";
        Map<String,String> param=new HashMap<>();
        param.put("q","响应302");
        String result=HttpClientUtil.doPost(url,param);
        System.out.println("结果展示:"+result);
    }
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、付费专栏及课程。

余额充值