java+httpclient的接口get、post、put、delete请求实现(基于IDEA的maven工程)

1、环境准备

将使用IDEA和maven完成本次接口请求实现,以下内容,将默认读者已完成环境准备,包括但不限于JDK、maven、IDEA,并熟练掌握他们的使用方法,如若有不清楚的请自行学习。

2、创建一个maven工程

在IDEA中新建一个maven工程,pom.xml文件中引入httpclient、httpmime、httpcore
在这里插入图片描述

3、get请求实现

public static final Charset CHARSET_DEFAULT = StandardCharsets.UTF_8;
/**
 * 无请求头信息的get()请求
 *
 * @param url API请求地址
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse get(String url) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
    } catch (IOException e) {
        LOGGER.error("get请求执行异常:\n");
        e.printStackTrace();
    }
    return response;
}

/**
 * 带请求头的get()请求
 *
 * @param url     API请求地址
 * @param headers 请求头,使用Map键值对方式传入
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse get(String url, HashMap<String, String> headers) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    for (HashMap.Entry<String, String> entry : headers.entrySet()) {
        httpGet.setHeader(entry.getKey(), entry.getValue());
    }
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
    } catch (IOException e) {
        LOGGER.error("get请求执行异常:\n");
        e.printStackTrace();
    }
    return response;
}


/**
 * 带请求头和额外参数的get()请求
 *
 * @param url        API请求地址
 * @param headers    请求头,使用Map键值对方式传入
 * @param parameters 请求参数使用NameValuePair键值对方式传入,使用方式如下
 *                   List<NameValuePair> parameters=new ArrayList<>();
 *                   parameters.add(new BasicNameValuePair("page","2")) ;
 *                   parameters.add(new BasicNameValuePair("token","tokenvalue")) ;
 *                   此方法需要所有的参数都在此传入不能一半直接写在url,一半在这里传参
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse get(String url, HashMap<String, String> headers, List<NameValuePair> parameters) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    URLEncodedUtils.format(parameters, CHARSET_DEFAULT);
    url = String.format("%s%s", url, new URIBuilder().addParameters(parameters));
    HttpGet httpGet = new HttpGet(url);
    for (HashMap.Entry<String, String> entry : headers.entrySet()) {
        httpGet.setHeader(entry.getKey(), entry.getValue());
    }

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
    } catch (IOException e) {
        LOGGER.error("get请求执行异常:\n");
        e.printStackTrace();
    }
    return response;
}

/**
 * 无请求头,有额外参数的get()请求
 *
 * @param url        API请求地址
 * @param parameters 请求参数使用NameValuePair键值对方式传入,使用方式如下
 *                   List<NameValuePair> parameters=new ArrayList<>();
 *                   parameters.add(new BasicNameValuePair("page","2")) ;
 *                   parameters.add(new BasicNameValuePair("token","tokenvalue")) ;
 *                   此方法需要所有的参数都在此传入不能一半直接写在url,一半在这里传参
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse get(String url, List<NameValuePair> parameters) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    URLEncodedUtils.format(parameters, CHARSET_DEFAULT);
    url = String.format("%s%s", url, new URIBuilder().addParameters(parameters));
    HttpGet httpGet = new HttpGet(url);

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
    } catch (IOException e) {
        LOGGER.error("get请求执行异常:\n");
        e.printStackTrace();
    }
    return response;
}

4、post请求实现

   /**
     * 无请求头,无参数信息的post()请求
     *
     * @param url API请求地址
     * @return 请求响应完整信息
     */
    public static CloseableHttpResponse post(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            LOGGER.error("post请求执行异常:" + url+ "\n");
            e.printStackTrace();
        }
        return response;
    }

/**
 * 带请求头、无参数的post()请求
 *
 * @param url     API请求地址
 * @param headers 请求头,使用Map键值对方式传入
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse post(String url, HashMap<String, String> headers) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    for (HashMap.Entry<String, String> entry : headers.entrySet()) {
        httpPost.setHeader(entry.getKey(), entry.getValue());
    }
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        LOGGER.error("post请求执行异常:" + url+ "\n");
        e.printStackTrace();
    }
    return response;
}


/**
 * 带请求头和参数的post()请求,通过表单(键值对)传参
 *
 * @param url        API请求地址
 * @param headers    请求头,使用Map键值对方式传入
 * @param parameters 请求参数使用NameValuePair键值对方式传入,使用方式如下
 *                   List<NameValuePair> parameters=new ArrayList<>();
 *                   parameters.add(new BasicNameValuePair("page","2")) ;
 *                   parameters.add(new BasicNameValuePair("token","tokenvalue")) ;
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse post(String url, HashMap<String, String> headers, List<NameValuePair> parameters) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, CHARSET_DEFAULT);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(entity);
    for (HashMap.Entry<String, String> entry : headers.entrySet()) {
        httpPost.setHeader(entry.getKey(), entry.getValue());
    }

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        LOGGER.error("post请求执行异常:" + url+ "\n");
        e.printStackTrace();
    }
    return response;
}

/**
 * 无请求头,有额外参数的post()请求,通过表单(键值对)传参
 *
 * @param url        API请求地址
 * @param parameters 请求参数使用NameValuePair键值对方式传入,使用方式如下
 *                   List<NameValuePair> parameters=new ArrayList<>();
 *                   parameters.add(new BasicNameValuePair("page","2")) ;
 *                   parameters.add(new BasicNameValuePair("token","tokenvalue")) ;
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse post(String url, List<NameValuePair> parameters) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, CHARSET_DEFAULT);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(entity);
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        LOGGER.error("post请求执行异常:" + url+ "\n");
        e.printStackTrace();
    }
    return response;
}

/**
 * 有请求头,有额外参数的post()请求,通过body传参
 *
 * @param url        API请求地址
 * @param headers    请求头,使用Map键值对方式传入
 * @param bodyEntity body请求实体
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse post(String url, HashMap<String, String> headers, String bodyEntity) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    StringEntity entity = new StringEntity(bodyEntity, CHARSET_DEFAULT);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(entity);
    for (HashMap.Entry<String, String> entry : headers.entrySet()) {
        httpPost.setHeader(entry.getKey(), entry.getValue());
    }
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        LOGGER.error("post请求执行异常:" + url+ "\n");
        e.printStackTrace();
    }
    return response;
}

/**
 * 无请求头,有额外参数的post()请求,通过body传参
 *
 * @param url        API请求地址
 * @param bodyEntity body请求实体
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse post(String url, String bodyEntity) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    StringEntity entity = new StringEntity(bodyEntity, CHARSET_DEFAULT);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(entity);
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        LOGGER.error("post请求执行异常:" + url+ "\n");
        e.printStackTrace();
    }
    return response;
}

5、带文件上传的post请求实现

/**
 * 带有文件上传的post请求,只有请求头与文件信息,没有额外参数
 *
 * @param url      API请求地址
 * @param headers  请求头,使用Map键值对方式传入
 * @param file     要上传的文件
 * @param pairName 上传文件对应的参数名称
 * @param fileType 上传文件对应的MIME类型,如 MIMEType.MIME_DOC
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse postUpload(String url, HashMap<String, String> headers, File file, String pairName, String fileType) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    //设置请求实体为浏览器兼容模式,防止上传中文文件名乱码
    HttpMultipartMode mode = HttpMultipartMode.BROWSER_COMPATIBLE;
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(mode);

    //实体中插入文件信息,设置编码方式
    ContentType fileContentType = ContentType.create(fileType, CHARSET_DEFAULT);
    multipartEntityBuilder.addBinaryBody(pairName, file, fileContentType, file.getName());
    multipartEntityBuilder.setCharset(CHARSET_DEFAULT);

    HttpEntity entity = multipartEntityBuilder.build();
    httpPost.setEntity(entity);

    for (HashMap.Entry<String, String> entry : headers.entrySet()) {
        httpPost.setHeader(entry.getKey(), entry.getValue());
    }

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        LOGGER.error("postUpload请求执行异常:" + url+ "\n");
        e.printStackTrace();
    }
    return response;
}

/**
 * 带有文件上传的post请求,除请求头与文件信息外,还包含有额外参数
 *
 * @param url        API请求地址
 * @param headers    请求头,使用Map键值对方式传入
 * @param parameters 请求参数使用NameValuePair键值对方式传入,使用方式如下
 *                   List<NameValuePair> parameters=new ArrayList<>();
 *                   parameters.add(new BasicNameValuePair("page","2")) ;
 *                   parameters.add(new BasicNameValuePair("token","tokenvalue")) ;
 * @param file       要上传的文件
 * @param pairName   上传文件对应的参数名称
 * @param fileType   上传文件对应的MIME类型,如 MIMEType.MIME_DOC
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse postUpload(String url, HashMap<String, String> headers, List<NameValuePair> parameters, File file, String pairName, String fileType) {

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

    //设置请求实体为浏览器兼容模式,防止上传中文文件名乱码
    HttpMultipartMode mode = HttpMultipartMode.BROWSER_COMPATIBLE;
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(mode);

    //实体中插入文件信息,设置编码方式
    ContentType fileContentType = ContentType.create(fileType, CHARSET_DEFAULT);
    multipartEntityBuilder.addBinaryBody(pairName, file, fileContentType, file.getName());
    multipartEntityBuilder.setCharset(CHARSET_DEFAULT);

    //实体中插入其他表单参数信息
    for (NameValuePair pair : parameters) {
        ContentType contentType = ContentType.create("text/plain", CHARSET_DEFAULT);
        StringBody value = new StringBody(pair.getValue(), contentType);
        multipartEntityBuilder.addPart(pair.getName(), value);
 //     multipartEntityBuilder.addTextBody(pair.getName(),pair.getValue()) ;  //使用这个会导致参数中文乱码
    }

    HttpEntity entity = multipartEntityBuilder.build();
    httpPost.setEntity(entity);
    //插入请求头信息
    for (HashMap.Entry<String, String> entry : headers.entrySet()) {
        httpPost.setHeader(entry.getKey(), entry.getValue());
    }
    CloseableHttpResponse response = null;
    try {
        //执行请求
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        LOGGER.error("postUpload请求执行异常:" + url+ "\n");
        e.printStackTrace();
    }
    return response;
}

/**
 * 带有文件上传的post请求,只文件信息和额外参数,没有请求头
 *
 * @param url        API请求地址
 * @param parameters 请求参数使用NameValuePair键值对方式传入,使用方式如下
 *                   List<NameValuePair> parameters=new ArrayList<>();
 *                   parameters.add(new BasicNameValuePair("page","2")) ;
 *                   parameters.add(new BasicNameValuePair("token","tokenvalue")) ;
 * @param file       要上传的文件
 * @param pairName   上传文件对应的参数名称
 * @param fileType   上传文件对应的MIME类型,如 MIMEType.MIME_DOC
 * @return 请求响应完整信息
 */
public static CloseableHttpResponse postUpload(String url, List<NameValuePair> parameters, File file, String pairName, String fileType) {

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

    //设置请求实体为浏览器兼容模式,防止上传中文文件名乱码
    HttpMultipartMode mode = HttpMultipartMode.BROWSER_COMPATIBLE;
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(mode);

    //实体中插入文件信息,设置编码方式
    ContentType fileContentType = ContentType.create(fileType, CHARSET_DEFAULT);
    multipartEntityBuilder.addBinaryBody(pairName, file, fileContentType, file.getName());
    multipartEntityBuilder.setCharset(CHARSET_DEFAULT);

    //实体中插入其他表单参数信息
    for (NameValuePair pair : parameters) {
        ContentType contentType = ContentType.create("text/plain", CHARSET_DEFAULT);
        StringBody value = new StringBody(pair.getValue(), contentType);
        multipartEntityBuilder.addPart(pair.getName(), value);
	//  multipartEntityBuilder.addTextBody(pair.getName(),pair.getValue()) ;  //使用这个会导致参数中文乱码
    }

    HttpEntity entity = multipartEntityBuilder.build();
    httpPost.setEntity(entity);

    CloseableHttpResponse response = null;
    try {
        //执行请求
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        LOGGER.error("postUpload请求执行异常:" + url+ "\n");
        e.printStackTrace();
    }
    return response;
}

6、put与delete 请求

put请求与post请求实现基本一致,把对应请求方式由post更换成put即可
delete请求与get请求实现基本一致,把对应的请求方式由get更换为delete即可

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值