post请求

post请求时,请求参数写入输出流中,url地址除去拼接参数后的地址,如:

"http://169.254.244.136/Web2/servlet/Login?name=" + URLEncoder.encode(name) + "&pass=" + pass;
正确地址:
String path = "http://169.254.244.136/Web2/servlet/Login"。
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 
conn.setRequestMethod("POST");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
 
//添加post请求头中自动添加的属性
//流里的数据的mimetype
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String content = "name=" + URLEncoder.encode(name) + "&pass=" + pass;//请求参数
//流里数据的长度
conn.setRequestProperty("Content-Length", content.length() + "");
//打开连接对象的输出流
conn.setDoOutput(true);
//获取连接对象的输出流
OutputStream os = conn.getOutputStream();
//把数据写入输出流中
os.write(content.getBytes());
 
if(conn.getResponseCode() == 200){
InputStream is = conn.getInputStream();
String text = Tools.getTextFromStream(is);
 
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
原文地址:https://www.cnblogs.com/SoulCode/p/6393426.html