android之使用get和post方式向服务器提交请求

通过get和post方式向服务器发送请求首先说一下get和post的区别get请求方式是将提交的参数拼接在url地址后面,例如?num=23&jjj=888;但是这种形式对于那种比较隐私的参数是不适合的,而且参数的大小也是有限制的,一般是1K左右吧,对于上传文件就不是很适合。post请求方式是将参数放在消息体内将其发送到服务器,所以对大小没有限制,对于隐私的内容也比较合适。如下Post请求POST /LoginCheck HTTP/1.1Accept: text/html, application/xhtml+xml, */*Referer: Accept-Language: zh-CNUser-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)Content-Type: application/x-www-form-urlencodedAccept-Encoding: gzip, deflateHost: 192.168.2.1Content-Length: 39Connection: Keep-AliveCache-Control: no-cacheCookie: language=enUsername=admin&checkEn=0&Password=admin //参数位置在android中用get方式向服务器提交请求:在android模拟器中访问本机中的tomcat服务器时,注意:不能写localhost,因为模拟器是一个单独的手机系统,所以要写真是的IP地址。否则无法访问到服务器。//要访问的服务器地址,下面的代码是要向服务器提交用户名和密码,提交时中文先要经过URLEncoder编码,因为模拟器默认的编码格式是utf-8//而tomcat内部默认的编码格式是ISO8859-1,所以先将参数进行编码,再向服务器提交。private String address = ":80/server/loginServlet";public boolean get(String username, String password) throws Exception {username = URLEncoder.encode(username);// 中文数据需要经过URL编码password = URLEncoder.encode(password);String params = "username=" + username + "&password=" + password;//将参数拼接在URl地址后面URL url = new URL(address + "?" + params);//通过url地址打开连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设置超时时间conn.setConnectTimeout(3000);//设置请求方式conn.setRequestMethod("GET");//如果返回的状态码是200,,则一切Ok,连接成功。return conn.getResponseCode() == 200;}在android中通过post方式提交数据。public boolean post(String username, String password) throws Exception {username = URLEncoder.encode(username);// 中文数据需要经过URL编码password = URLEncoder.encode(password);String params = "username=" + username + "&password=" + password;byte[] data = params.getBytes();URL url = new URL(address);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(3000);//这是请求方式为POSTconn.setRequestMethod("POST");//设置post请求必要的请求头conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 请求头, 必须设置conn.setRequestProperty("Content-Length", data.length + "");// 注意是字节长度, 不是字符长度conn.setDoOutput(true);// 准备写出conn.getOutputStream().write(data);// 写出数据return conn.getResponseCode() == 200;}

人要想成为生活的主人,不仅要适应生活,而且还要发挥主动性,

android之使用get和post方式向服务器提交请求

相关文章:

你感兴趣的文章:

标签云: