现在的位置: 首页 > 综合 > 正文

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

2017年05月18日 ⁄ 综合 ⁄ 共 2101字 ⁄ 字号 评论关闭

通过get和post方式向服务器发送请求

首先说一下get和post的区别

get请求方式是将提交的参数拼接在url地址后面,例如http://www.baidu.com/index.jsp?num=23&jjj=888;
但是这种形式对于那种比较隐私的参数是不适合的,而且参数的大小也是有限制的,一般是1K左右吧,对于上传文件
就不是很适合。

post请求方式是将参数放在消息体内将其发送到服务器,所以对大小没有限制,对于隐私的内容也比较合适。

如下Post请求


POST /LoginCheck HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://192.168.2.1/login.asp
Accept-Language: zh-CN
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: 192.168.2.1
Content-Length: 39
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: language=en

Username=admin&checkEn=0&Password=admin //参数位置
在android中用get方式向服务器提交请求:

在android模拟器中访问本机中的tomcat服务器时,注意:不能写localhost,因为模拟器是一个单独的手机系统,所以要写真是的IP地址。
否则无法访问到服务器。

//要访问的服务器地址,下面的代码是要向服务器提交用户名和密码,提交时中文先要经过URLEncoder编码,因为模拟器默认的编码格式是utf-8
//而tomcat内部默认的编码格式是ISO8859-1,所以先将参数进行编码,再向服务器提交。

GET

private String address = "http://192.168.2.101: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);
//这是请求方式为POST
conn.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;
}

抱歉!评论已关闭.