1,URL url =
new
URL(path);
2,通过url获取连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
3,设置请求方式:
conn.setRequestMethod(GET);
4,设置连接超时:
conn.setConnectTimeout(
5000
);
5,设置请求头的信息:
conn.setRequestProperty(User-Agent, Mozilla/
5.0
(compatible; MSIE
9.0
; Windows NT
6.1
; Trident/
5.0
));
6,获取响应码:
int
code = conn.getResponseCode();
7,针对不同的响应码,做不同的操作:
请求码200,表明请求成功,获取返回内容的输入流:InputStream is = conn.getInputStream();
将输入流转换成字符串:
public
class
StreamTools {
/**
* 将输入流转换成字符串
*
* @param is
* 从网络获取的输入流
* @return
*/
public
static
String streamToString(InputStream is) {
try
{
ByteArrayOutputStream baos =
new
ByteArrayOutputStream();
byte
[] buffer =
new
byte
[
1024
];
int
len =
0
;
while
((len = is.read(buffer)) != -
1
) {
baos.write(buffer,
0
, len);
}
baos.close();
is.close();
byte
[] byteArray = baos.toByteArray();
return
new
String(byteArray);
}
catch
(Exception e) {
Log.e(tag, e.toString());
return
null
;
}
}
}
|
若返回值400,则是返回网络异常,做出响应的处理。
1、
HttpUrlConnection发送POST请求
/**
* 通过HttpUrlConnection发送POST请求
*
* @param username
* @param password
* @return
*/
public
static
String loginByPost(String username, String password) {
String path = http:
//192.168.0.107:8080/WebTest/LoginServerlet;
try
{
URL url =
new
URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(
5000
);
conn.setRequestMethod(POST);
conn.setRequestProperty(Content-Type, application/x-www-form-urlencoded);
String data = username= + username + &password= + password;
conn.setRequestProperty(Content-Length, data.length() + );
// POST方式,其实就是浏览器把数据写给服务器
conn.setDoOutput(
true
);
// 设置可输出流
OutputStream os = conn.getOutputStream();
// 获取输出流
os.write(data.getBytes());
// 将数据写给服务器
int
code = conn.getResponseCode();
if
(code ==
200
) {
InputStream is = conn.getInputStream();
return
StreamTools.streamToString(is);
}
else
{
return
网络访问失败;
}
}
catch
(Exception e) {
e.printStackTrace();
return
网络访问失败;
}
}
HttpUrlConnection发送GET请求
/**
* 通过HttpUrlConnection发送GET请求
*
* @param username
* @param password
* @return
*/
public
static
String loginByGet(String username, String password) {
String path = http:
//192.168.0.107:8080/WebTest/LoginServerlet?username= + username + &password= + password;
try
{
URL url =
new
URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(
5000
);
conn.setRequestMethod(GET);
int
code = conn.getResponseCode();
if
(code ==
200
) {
InputStream is = conn.getInputStream();
// 字节流转换成字符串
return
StreamTools.streamToString(is);
}
else
{
return
网络访问失败;
}
}
catch
(Exception e) {
e.printStackTrace();
return
网络访问失败;
}
}