-- 创造无限可能

java 使用HttpClients方式发送http请求

2023-08-03 11:32:16
478 人浏览 1 人点赞
有用,点赞支持一下

使用httClients发送post请求
`

/**
 * 使用httClients发送post请求
 * @param url 请求的url地址
 * @param list 需要发送的请求参数(需要一个ArrList)
 */
public String httpPost(String url, List list) throws Exception {

    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;

    try{
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);


        // 设置请求参数,可通过在接口传入
//            List<NameValuePair> list = new ArrayList<>();
//            list.add(new BasicNameValuePair("param1", "value1"));
//            list.add(new BasicNameValuePair("param2", "value2"));

        UrlEncodedFormEntity params = new UrlEncodedFormEntity(list, "UTF-8");

        //设置请求参数
        httpPost.setEntity(params);


        //发送http请求
        response = httpClient.execute(httpPost);

        //判断响应状态码
        if(response.getStatusLine().getStatusCode() == 200){
            //响应数据
            HttpEntity entity = response.getEntity();

            //将响应数据以字符串方式展示
            String html = EntityUtils.toString(entity, "UTF-8");

            return html;
        }

        //失败
        return "error";

    } catch (Exception exception){
        exception.printStackTrace();
        throw new Exception(exception.getMessage());
    }finally {
        try{
            //关闭资源
            httpClient.close();
            response.close();
        } catch (IOException e){
            //e.printStackTrace()方法介绍
            //当Java程序抛出异常时,它会在调用堆栈中创建一个异常对象并将其抛出。使用e.printStackTrace()方法可以打印出这个异常对象所在的调用堆栈,包括哪个类的哪个方法抛出了异常,以及异常被传播的路径。
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }

}`

发送get请求

public String httpGet(){

    //get请求直接写在地址拼接 (栗子:http://www.baidu.com?name=zhangsan&age=18)
    String url = "http://www.ttxtc.com";

    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;

    try{
        httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        //发送http请求
        response = httpClient.execute(httpGet);

        //判断响应状态码
        if(response.getStatusLine().getStatusCode() == 200){
            //响应数据
            HttpEntity entity = response.getEntity();

            //将响应数据以字符串方式展示
            String html = EntityUtils.toString(entity, "UTF-8");

            return html;
        }
    } catch (Exception exception){
        exception.printStackTrace();
    }finally {
        try{
            //关闭资源
            httpClient.close();
            response.close();
        } catch (IOException e){
            //e.printStackTrace()方法介绍
            //当Java程序抛出异常时,它会在调用堆栈中创建一个异常对象并将其抛出。使用e.printStackTrace()方法可以打印出这个异常对象所在的调用堆栈,包括哪个类的哪个方法抛出了异常,以及异常被传播的路径。
            e.printStackTrace();
        }
    }


}`