java发送http请求的两种方式:HTTPClient和CloseableHttpClient

2 篇文章 0 订阅

java发送http请求有三种方式,除了原生连接方式HttpURLConnection,还有另外两种方式:HTTPClient和CloseableHttpClient
下面分别简单介绍使用HTTPClient和CloseableHTTPClient进行Get和Post请求的方式。
详情使用链接

HttpClient

使用commons-httpclient.jar,maven依赖如下:

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>

简单代码如下:

private static String doGet(String url) {
    String res = null;
    HttpClient client = new HttpClient();
    GetMethod getMethod = new GetMethod(url);
    int code = 0;
    try {
        code = client.executeMethod(getMethod);
        if (code == 200) {
            res = getMethod.getResponseBodyAsString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}
private static String doPost(String url, Map<String, Object> paramMap) {
    String res = null;
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setContentCharset("UTF-8");
    Iterator<Map.Entry<String, Object>> iterator = paramMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, Object> next = iterator.next();
        postMethod.addParameter(next.getKey(), next.getValue().toString());
    }
    try {
        int code = client.executeMethod(postMethod);
        if (code == 200) {
            res = postMethod.getResponseBodyAsString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}
public static void main(String[] args) {
    //get
    System.out.println(doGet("http://localhost:8080/hello"));

    //post
    //设置传入参数的格式:请求参数是 map 的形式
    Map<String, Object> paramMap = new HashMap<>(2);
    paramMap.put("name", "赵云");
    paramMap.put("age", 21);
    System.out.println(doPost("http://localhost:8080/hello1", paramMap));
}

被调用方法:
在这里插入图片描述
测试结果:
在这里插入图片描述
在这里插入图片描述

CloseableHttpClient

使用httpclient.jar,maven依赖如下:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

简单代码如下:

/**
 * 发送HttpGet请求
 * @param url
 * @return
 */
public static String doGet(String url) {
    //1.获得一个httpclient对象
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //2.生成一个get请求
    HttpGet httpget = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {
        //3.执行get请求并返回结果
        response = httpclient.execute(httpget);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    String result = null;
    try {
        //4.处理结果,这里将结果返回为字符串
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity);
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}
/**
 * 发送HttpPost请求,参数为map
 * @param url
 * @param map
 * @return
 */
public static String doPost(String url, Map<String, Object> map) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        //给参数赋值
        formparams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
    }
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(entity);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (IOException e) {
        e.printStackTrace();
    }
    HttpEntity entity1 = response.getEntity();
    String result = null;
    try {
        result = EntityUtils.toString(entity1);
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    }
    return result;
}
public static void main(String[] args) {
    //get
    System.out.println(doGet("http://localhost:8080/hello"));

    //post
    //设置传入参数的格式:请求参数是 map 的形式
    Map<String, Object> paramMap = new HashMap<>(2);
    paramMap.put("name", "张飞");
    paramMap.put("age", 55);
    System.out.println(doPost("http://localhost:8080/hello1", paramMap));
}

被调用方法:

在这里插入图片描述
测试结果:
在这里插入图片描述
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值