post请求服务器原理:首先要设置请求方式,然后设置要带的参数,设置content-type和content-length,然后告诉服务器要写数据了,最后将数据写进请求体中。post的要复杂一样,但是安全。

new Thread(){

public void run() {

try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

//'设置请求方式为post
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);

// Content-Type: application/x-www-form-urlencoded 设置content-type
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

//传送的数据  ---- number=123&pwd=456
String data = "number="+URLEncoder.encode(number, "utf-8")+"&pwd="+URLEncoder.encode(pwd, "utf-8");


     //Content-Length: 20  设置content-length
conn.setRequestProperty("Content-Length", data.length()+"");

//这个 地方 表示 告诉  加了一个标志, 要给 服务器写 数据了 
conn.setDoOutput(true);

conn.getOutputStream().write(data.getBytes());

// http post 是面向 http协议的过程 去 写的 

int code = conn.getResponseCode();

if(code==200){

InputStream in = conn.getInputStream();

String data2 = StreamTool.decodeStream(in);

Message msg = Message.obtain();
msg.what=SUCCESS;
msg.obj = data2;
mHandler.sendMessage(msg);
}

} catch (Exception e) {
e.printStackTrace();
Message msg = Message.obtain();
msg.what=ERROR;
mHandler.sendMessage(msg);
}

};
}.start();

      区别:和get差不多,但是存放数据的地方不一样,get的数据一般在url后面,post的数据是在请求体里面,post请求体里面多了content-type和content-length,所以在访问服务器的时候需要设定下这两个属性的值。

post方式访问服务器及与get方式的区别

相关文章: