使用HttpClient发送DELETE请求,支持带参数

这篇博客介绍了如何在Java中使用HttpClient发送带参数的DELETE请求。由于HttpClient的HttpDelete不支持直接携带参数,作者自定义了一个HttpDeleteWithBody类,通过设置Content-Type为application/json或multipart/form-data来发送JSON或表单数据。示例代码展示了如何以这两种方式发送请求,并获取响应结果。
摘要由CSDN通过智能技术生成

1.自定义HttpDelete类

HttpClient中DELETE请求,是没有办法带参数的。因为setEntity()方法是抽象类HttpEntityEnclosingRequestBase类里的方法,HttpPost继承了该类,而HttpDelete类继承的是HttpRequestBase类。所以是没有setEntity()方法的。

需要自己创建一个新类,然后照着HttpPost的抄一遍,让新类能够调用setEntity()方法

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;

class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {

    public static final String METHOD_NAME = "DELETE";

    /**
     * 获取方法(必须重载)
     *
     * @return
     */
    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

    public HttpDeleteWithBody(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    public HttpDeleteWithBody(final URI uri) {
        super();
        setURI(uri);
    }

    public HttpDeleteWithBody() {
        super();
    }
}

2.1 采用JSON方式(application/json)发送请求

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public static void main(String[] args) throws Exception{

    String url = "";// 地址
    Map<String,String> params = new HashMap<>();// 参数
    params.put("param1","");

    // 创建默认的httpClient实例.
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //以delte方式请求
    HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);

    // 设置请求头
    httpDelete.setHeader("Content-Type", "application/json;charset=UTF-8");
    httpDelete.setHeader("accept","application/json");

    //将参数以UTF-8编码并包装成表单实体对象
    StringEntity se = new StringEntity(new Gson().toJson(params), "UTF-8");
    se.setContentType("text/json");
    httpDelete.setEntity(se);

    // 执行请求
    CloseableHttpResponse response = httpClient.execute(httpDelete);

    // 获取返回值
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity, "UTF-8");
    System.out.println("打印结果:"+result);
}

2.2 采用表单方式(multipart/form-data)发送请求

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public static void main(String[] args) throws Exception{
    String url = "";// 地址
    Map<String,String> params = new HashMap<>();// 参数
    params.put("param1","");

    // 创建默认的httpClient实例.
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //以delte方式请求
    HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
    
    // 设置请求头
    // Content-Type设置成multipart/form-data,服务器反而取不到参数
    // 目前不清楚原因,猜测可能是使用了UrlEncodedFormEntity引起的
    // httpDelete.setHeader("Content-Type", "multipart/form-data");
    httpDelete.setHeader("accept","application/json");

    // 组织请求参数
    List<NameValuePair> paramList = new ArrayList <NameValuePair>();
    if(params != null && params.size() > 0){
        Set<String> keySet = params.keySet();
        for(String key : keySet) {
            paramList.add(new BasicNameValuePair(key, params.get(key)));
        }
    }
    httpDelete.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));

    // 执行请求
    CloseableHttpResponse response = httpClient.execute(httpDelete);

    // 获取返回值
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity, "UTF-8");
    System.out.println("打印结果:"+result);
}

参考地址:

https://blog.csdn.net/u012843873/article/details/106900612

使用HttpClient 发送 GET、POST(FormData、Raw)、PUT、Delete请求及文件上传 - iFindU_San - 博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值