Java+HttpClient学习笔记05-POST请求

JSON格式的请求

使用了GitHub的添加邮箱的接口进行测试,GitHub接口文档

先登录GitHub,然后右上角用户下拉框中选择settings,然后选Emails。可以看到当前账户设置的邮箱情况

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

再看添加邮箱接口的文档描述,可以通过一个str或者一个数组来添加一个,或多个邮箱

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.client.methods.HttpPost;
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.*;

public class LessonPost {
	//返回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","password");
		//创建内置httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();
		//创建POST请求对象
		HttpPost httpPost = new HttpPost("https://api.github.com/user/emails");
		//添加请求头
		httpPost.addHeader("Authorization",str);
		httpPost.addHeader("Content-Type", "application/json");
		//JSON格式的请求实体
		JSONObject jsonObject = new JSONObject();
		List list = new ArrayList<>();
                //想要添加的邮箱
		list.add("email");
		jsonObject.put("emails",list);
		//设置请求实体
		httpPost.setEntity(new StringEntity(JSON.toJSONString(jsonObject),"utf-8"));
		//发送请求,获得响应内容
		CloseableHttpResponse response = client.execute(httpPost);
		try {
			System.out.println(response.getStatusLine());
			//响应实体
			HttpEntity entity = response.getEntity();
			//实体内容
			System.out.println(EntityUtils.toString(entity));
		}finally {
			response.close();
		}


	}
}

Java+HttpClient学习笔记05-POST请求_第2张图片

需要使用StringEntity,将转为String的json设置为请求实体

 

不使用JSON格式,使用表单,找不到合适的接口测试。

		List list1 = new ArrayList<>();
		BasicNameValuePair bnvp = new BasicNameValuePair("emails","email");
		list1.add(bnvp);
		httpPost.setEntity(new UrlEncodedFormEntity(list1,"UTF-8"));

创建一个NameValuePair类型的数组,然后添加BasicNameValuPair这样的数据进去,再使用UrIEncodedFormEntity()

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