1.请求的URL地址不同
get: http://10.0.2.2:8080/HttpTest/index.jsp?option=getUser&uName=jerehedu
post: http://10.0.2.2:8080/HttpTest/index.jsp
2.post方式多了对请求头的设置
//设置一些请求头的信息 field:http请求的请求头 newValue:请求头的值
httpURLConnection.setRequestProperty("Charset","UTF-8");
httpURLConnection.setRequestProperty("Content-type","application/x-www-form-urlencoded");
3.post方式还多了请求的内容—option=getUser&uName=jerehedu,而get方式的相应内容在URL地址中
//设置httpURLConnection可以请求的内容
httpURLConnection.setDoOutput(true);
//option=getUser&uName=jerehedu
String params=args;
//获取一个outputstream,并将内容写入该流
OutputStream os=httpURLConnection.getOutputStream();
4.请求时携带的内容大小不同
get:1k
post:理论上无限制
即post适合传大量数据
5.get方式的数据直接明文显示在URL地址中,是不安全的;而post方式则不会,安全性相对较高
get方式的代码:
public static String doGet(String u){
HttpURLConnection con=null;
InputStream is=null;
StringBuilder sbd=new StringBuilder();
try {
URL url=new URL(u);
con= (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5*1000); //设置超时时间
con.setReadTimeout(5*1000); //设置读取时间
// con.setRequestMethod("GET");
if(con.getResponseCode()==200){ //判断是否连接成功
is=con.getInputStream(); //获取输入
int next=0;
byte[] bt=new byte[1024];
while((next=is.read(bt))!=-1){
sbd.append(new String(bt),0,next); //读入到sbd中
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(con!=null){
con.disconnect();
}
}
return sbd.toString();
}
post方式的代码:
public static String doPost(String uri,String args){
HttpURLConnection httpURLConnection=null;
InputStream is=null;
StringBuilder sbd=new StringBuilder();
try {
URL url=new URL(uri);
httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5*1000);
httpURLConnection.setReadTimeout(5*1000);
httpURLConnection.setRequestMethod("POST");
//设置httpURLConnection可以请求的内容
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
//设置一些请求头的信息 field:http请求的请求头 newValue:请求头的值
httpURLConnection.setRequestProperty("Charset","UTF-8");
httpURLConnection.setRequestProperty("Content-type","application/x-www-form-urlencoded");
//option=getUser&uName=jerehedu
String params=args;
//获取一个outputstream,并将内容写入该流
OutputStream os=httpURLConnection.getOutputStream();
os.write(params.getBytes());
os.flush();
os.close();
if(httpURLConnection.getResponseCode()==200){
is=httpURLConnection.getInputStream();
int next=0;
byte[] b=new byte[1024*10];
while((next=is.read(b))>0){
sbd.append(new String(b,0,next));
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(is!=null){
is.close();
}
if(httpURLConnection!=null){
httpURLConnection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sbd.toString();
}