HttpURLConnection 带参数请求接口

public static String requestPost(String url, Map<String, String> map) {
BufferedReader reader = null;
String line = null;
HttpURLConnection httpURLConnection = null;
try {
URL postUrl = new URL(url);
// 打开连接
httpURLConnection = (HttpURLConnection) postUrl.openConnection();
// 设置是否向connection输出,因为这个是post请求,参数要放在请求体中
// http正文内,因此需要设为true
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");// 设置为post请求
httpURLConnection.setUseCaches(false);
httpURLConnection.setInstanceFollowRedirects(true);
// 已form表单的形式传递传递参数 默认可以不传
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// OutputStream outputStream = connection.getOutputStream();
// 具有隐性连接效应
httpURLConnection.connect(); // 配置请求信息需要在连接直接配置 顺序不可颠倒
DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
StringBuffer sBuffer = new StringBuffer();
for (String key : map.keySet()) {
sBuffer.append(key + "=" + map.get(key) + "&");
}
out.writeBytes(sBuffer.toString());
// 关闭流
out.flush();
out.close();
// 获取响应
reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
// //获得请求数据之后关闭连接
while ((line = reader.readLine()) != null) {
return line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭流关闭连接
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return line;


注意:该请求试用于post请求编码格式为utf8    后面继续更新不同请求方式以及不同格式的请求内容



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值