Java+HttpClient学习笔记06-DELETE请求

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

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

 

这是照抄之后的代码

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();
	}

}

 

测试的接口是GitHub删除邮箱的接口

Java+HttpClient学习笔记06-DELETE请求_第1张图片

这是执行DELETE请求的代码,执行之后估计会报错,因为这个接口的返回好像没有实体,可以从界面上看是删除成功了的。或者对这个接口再执行下GET请求,会返回账号当前绑定的邮箱。

代码中需要使用自己的GitHub的用户名和密码,邮箱需要是在该账号绑定的邮箱。

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class LessonDelete {
	//返回Authorization所需要的值
	public static String getAuthorization(String username, String password) throws UnsupportedEncodingException {
		//拼接成用户名:密码形式
		String str = username +":"+ password;
		//经过Base64编码
		String str1 = Base64.getEncoder().encodeToString(str.getBytes("UtF-8"));
		String str2 = "Basic "+ str1;
		return str2;
	}
	public static void main(String[] args) throws IOException {
		//获得经过编码的内容 GitHub的用户名密码
		String str = getAuthorization("username","passwrod");
		//创建内置httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();
		//创建DELETE请求对象
		HttpDeleteWithBody httpDelete = new HttpDeleteWithBody("https://api.github.com/user/emails");
		//添加请求头
		httpDelete.addHeader("Authorization",str);
		httpDelete.addHeader("Content-Type", "application/json");
		//JSON格式的请求实体
		JSONObject jsonObject = new JSONObject();
		List list = new ArrayList<>();
		list.add("[email protected]");
		jsonObject.put("emails",list);
		//设置请求实体
		httpDelete.setEntity(new StringEntity(JSON.toJSONString(jsonObject),"UTF-8"));
		//发送请求,获得响应内容
		CloseableHttpResponse response = client.execute(httpDelete);
		try {
			System.out.println(response.getStatusLine());
			//响应实体
			HttpEntity entity = response.getEntity();
			//实体内容
			System.out.println(EntityUtils.toString(entity));
		}catch (IllegalArgumentException e){
			System.out.println("Entity may not be null");
		}
		finally {
			response.close();
		}
	}
}

 

你可能感兴趣的:(Java+HttpClient)