java 原生java.net.Url POST请求
1.关键代码
- 请求链接 URL u = new URL(“http://www.bowen-tech.top“);
- 设置发送数据的格式为form表单 conn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded; charset=UTF-8”);
- 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true connection.setDoOutput(true);
- 防止乱码,设置编码为UTF-8
BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream(), “utf-8”));
public static String getPost(Map<String, Object> params) throws Exception {
//请求链接
URL u = new URL("http://www.bowen-tech.top");
//获取连接对象
HttpURLConnection conn=(HttpURLConnection) u.openConnection();
conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0))");
conn.setRequestProperty("Referer"," http://www.bowen-tech.top");
conn.setRequestProperty("Cookie", "");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // 设置发送数据的格式为form表单
conn.setRequestProperty("timeout","3000");
conn.setDoOutput(true);
conn.setRequestMethod("POST"); // 设置请求方式
// 打开请求正文输出流
OutputStream os = conn.getOutputStream();
// 写入输出数据,刷新缓存,关闭输出流
// StringBuilder content = "字段名=" + URLEncoder.encode("字符串值", "编码");
StringBuilder content = new StringBuilder();
for (String key : params.keySet()) {
content.append(key+"="+ params.get(key)+"&");
}
System.out.println(content.toString());
os.write(content.toString().getBytes());
os.flush();
os.close();
// 7. 发起请求并获取请求响应状态码
int responseCode = conn.getResponseCode();
StringBuffer sb=new StringBuffer();
//获取输入流
BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf-8"));
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
System.out.println(sb.toString());
return sb.toString();
}