Java HttpClient发送Post Get请求

在前面的多数博客中,都有介绍发送HTTP请求的方法,今天出一个极简版本的,平时用来一些连接测试。

Get请求

public static void main(String[] args) throws IOException {
	//这个是我的网站域名,啥也没有。各位大佬不要拿我做压力测试谢谢!
    String url = "https://www.marsdl.com";
    
    HttpClient httpClient = HttpClients.custom().build();
    HttpGet get = new HttpGet(url);
    
    HttpResponse response = httpClient.execute(get);
    HttpEntity resp_entity = response.getEntity();
    resp_entity.getContent();
    
    String resp_content = EntityUtils.toString(resp_entity,
     StandardCharsets.UTF_8);
    
    System.out.println(resp_content);
}

HttpGet实例的对象中可以添加头

get.setHeader("Accept-Encoding", "gzip, deflate");
get.setHeader("Accept-Language", "zh-CN,zh;q=0.8,fr;q=0.6,zh-TW;q=0.4");
get.setHeader("Cache-Control", "no-cache");
get.setHeader("Connection", "keep-alive");
get.setHeader("Host", "www.ximalaya.com");
get.setHeader("Pragma", "no-cache");

post请求

//初始化post请求
String sendUrl = "http://";
HttpPost post = new HttpPost(sendUrl)

post请求,传递body参数

//body参数
JSONObject paramsMap = new JSONObject();
paramsMap.put("playTimes","1");
paramsMap.put("appId", "xxxxxxxxxxx");
paramsMap.put("accountId", "xxxxxxxxxxx");

StringEntity entity = new StringEntity(paramsMap.toJSONString(),
 StandardCharsets.UTF_8);
 
entity.setContentType("application/json");
//生成的body添加到HttpPost中
post.setEntity(entity);

添加post请求的header

post.addHeader("content-type", "application/json");
post.addHeader("Connection", "Keep-Alive");
post.addHeader("Accept", "application/json");

发送请求获得结果

HttpClient httpClient = HttpClients.custom().build();
HttpResponse response = httpClient.execute(post);

String content = EntityUtils.toString(response.getEntity(), 
 StandardCharsets.UTF_8);

在调用RESTFul接口时,会有一些token验证。目前大多数的加密方式就几种。这几种我总结在这篇博客中,欢迎查看。点击查看博客内容

水平原因可能存在错误,希望指正 chenrui@marsdl.com

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值