学习Java web的时候总是背GET和POST的区别,根本不知道GET和POST有什么区别!
百度一下它们的区别就有答案!但是不能理解!
POST的代码:
public void run() {
String path = "http://10.31.2.6:8080/06_Server/servlet/login";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
/**
* 设置POST请求特殊的东西
* name="+ URLEncoder.encode(name) +"&pass=" + pass
*/
//拼接出要提交的数据的字符串
String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass;
//添加post请求的两行属性
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length() + "");
//将协议体提交给服务器
//打开输出流
conn.setDoOutput(true);
//拿到输出流
OutputStream os = conn.getOutputStream();
//放到输出流中,提交到服务器
os.write(data.getBytes());
conn.connect();
if(conn.getResponseCode() == 200) {
InputStream in = conn.getInputStream();
//将输入流变成字符串
String result = Utils.fromStream2String(in);
Message msg = handler.obtainMessage();
msg.obj = result;
handler.sendMessage(msg);
} else {
System.out.println("系统出错");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
GET的代码:
public void run() {
String path = "http://10.31.2.6:8080/06_Server/servlet/login?name="+ URLEncoder.encode(name) +"&pass=" + pass;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.connect();
if(conn.getResponseCode() == 200) {
InputStream in = conn.getInputStream();
//将输入流变成字符串
String result = Utils.fromStream2String(in);
Message msg = handler.obtainMessage();
msg.obj = result;
handler.sendMessage(msg);
} else {
System.out.println("系统出错");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
代码中就体现了GET和POST请求的区别!
来源:oschina
链接:https://my.oschina.net/u/2287186/blog/491970