HttpClient中DELETE请求,是没有办法带参数的。因为setEntity()方法是抽象类HttpEntityEnclosingRequestBase类里的方法,HttpPost继承了该类,而HttpDelete类继承的是HttpRequestBase类。下面是没有setEntity()方法的。
需要自己创建一个新类,然后照着HttpPost的抄一遍,让新类能够调用setEntity()方
法
自定义一个HttpDeleteWithBody类:
package com.connection.croller.delete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
@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();
}
}
用HttpClient 调用 HttpDeleteWithBody的方法,就可以进行body的操作了
package com.connection.croller.delete;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* delete
* 删除数据源
* */
public class DeleteConnection {
public static void main(String[] args)
{
DeleteConnection deleteConnection = new DeleteConnection();
deleteConnection.doDelete();
}
public String doDelete()
{
CloseableHttpClient client = HttpClients.createDefault();
HttpDelete delete = new HttpDelete("http://113.207.43.87:9090/api/servers/30");
delete.setHeader("Content-Type","application/json");
delete.setHeader("Authorization","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoicm9vdCIsImV4cCI6MTYyODgxNjAzNCwidXNlcklkIjoxfQ.zso4mmbKE6deAmk4CpOlSDouEImLvqApm7irOArmKKE");
try {
CloseableHttpResponse response = client.execute(delete);
String result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
return result;
} catch (IOException e) {
e.printStackTrace();
return "没有获取到返回值";
}finally {
try {
// 释放资源
if (client != null) {
client.close();
}
// if (response != null) {
// response.close();
// }
} catch (IOException e) {
e.printStackTrace();
}
}
}
}