HttpURLConnection 带参数请求接口

public static String requestPost(String url, Map 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    后面继续更新不同请求方式以及不同格式的请求内容



你可能感兴趣的:(url,请求接口工具类)