代码中发起请求

代码中发起get或post请求
1.java原生的发起请求,通过IO流进行数据的写入写出,
String strUrl = “xxx”;
try{
//建立连接
URL url = new URL(strUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
}catch (Exception e){
e.printStackTrace();
}
2.通过httpclient开源框架建立连接
HTTPClient可以理解为浏览器,但不是浏览器,想发起请求,必须先有浏览器,再确定是get还是post请求,是否有参数.
发起请求时,请求头中content-type必须要确定,确定要传输的数据是什么类型-application/json,Multipart等,还要设置字符类型(charset),不然会有乱码.
//创建浏览器
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//发起请求
HttpPost httpPost = new HttpPost(“xxxxx”);
//设置请求头,和将参数set到请求实体中
httpPost.setHeader(“Content-Type”,“application/json;charset=utf8”);
User user = new User();
//转为json串
String jsonUser = JSON.toJSONString(user );
StringEntity StringEntity = new StringEntity(jsonUser,“UTF-8”);
httpPost.setEntity(StringEntity);
//相应模型
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
HttpEntity str = response.getEntity();
}catch (Exception e){
e.printStackTrace();
}
//关闭资源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值