1、Get方式,该方式向服务器传递数据是直接把数据拼接在URL后面。获取数据是直接读取流。
/**
* Get方式请求数据
* @param urlStr
* @return
*/
public static String get(String urlStr) {
HttpURLConnection conn = null;
try {
// 发送给服务器的参数直接拼接在URL的后面
// http://192.168.0.110/app/index?username=XX&password=XX
URL url = new URL(urlStr);
// 获得HttpURLConnection对象
conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
conn.setRequestMethod("GET");
// 连接最长时间为10S
conn.setConnectTimeout(10 * 1000);
// 读取数据的时间为6S
conn.setReadTimeout(6 * 1000);
// 获得服务器返回的响应吗
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 请求成功,获取输入流,读取服务器返回的字符串
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = -1;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
String result = baos.toString();
baos.close();
return result;
// 如果是获取服务器返回的图片,直接使用
// Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
2、Post方式,向服务器传递数据是以流的方式往服务器写数据,也可以带在请求头里面。获取数据也是读取流。
/**
* Post方式请求数据
* @param urlStr
* @return
*/
public static String post(String urlStr) {
HttpURLConnection conn = null;
try {
// 发送给服务器的参数不能拼接在URL后面,而是以流的方式写入
// http://192.168.0.110/app/index
URL url = new URL(urlStr);
// 获得HttpURLConnection对象
conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
conn.setRequestMethod("POST");
// 连接最长时间为10S
conn.setConnectTimeout(10 * 1000);
// 读取数据的时间为6S
conn.setReadTimeout(6 * 1000);
// 设置为输出流,默认是不会的
conn.setDoOutput(true);
// 设置请求头信息
// conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 往服务器写数据
OutputStream os = conn.getOutputStream();
String data = "username=XX&password=XX";
os.write(data.getBytes());
// 获得服务器返回的响应吗
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 请求成功,获取输入流,读取服务器返回的字符串
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = -1;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
String result = baos.toString();
baos.close();
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
3、GET和POST的区别
- GET传送的数据量较小,不能大于2KB(这主要是因为受URL长度限制)。POST传送的数据量较大,一般被默认为不受限制。但理论上,限制取决于服务器的处理能力。
- GET 安全性较低,POST安全性较高。因为GET在传输过程,数据被放在请求的URL中,而如今现有的很多服务器、代理服务器或者用户代理都会将请求URL记 录到日志文件中,然后放在某个地方,这样就可能会有一些隐私的信息被第三方看到。另外,用户也可以在浏览器上直接看到提交的数据,一些系统内部消息将会一 同显示在用户面前。POST的所有操作对用户来说都是不可见的。