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

JSON格式的请求

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

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

再看添加邮箱接口的文档描述,可以通过一个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<String> 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();
		}


	}
}

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

 

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值