您的位置:首页 > 理论基础 > 计算机网络

网络请求测试之HttpUrlConnection【Android】

2016-08-01 16:48 369 查看
使用HttpConnection

1.URL:包含请求地址的类

url(path):包含请求路径的构造方法

openConnection():得到连接对象

2.HttpURLConnection:代表与服务器连接的类

setMethod("GET/POST"):设置请求方式

setConnectionTimeout(time):设置连接超时时间,单位为ms

setReadTimeout(time):设置读取服务器返回数据的时间

connect():连接服务器

int getResponseCode():得到服务器返回的结果吗

int getContentLength():得到服务器返回数据的长度(字节)

getOutputStream():返回一个指向服务器端的数据输出流

getInputStream():返回一个从服务器端返回的数据输入流

disconnect():断开连接

get请求

//显示ProgressDialog
final ProgressDialog dialog = ProgressDialog.show(netActivity.this,null,"正在请求中...");
//启动分线程
new Thread() {
@Override
public void run() {
//在分线程,发送请求,得到响应数据
try {
//得到path
String path = et_net_url.getText().toString()+"?name=Tom&age=12";
//创建URL对象
URL url = new URL(path);
//打开连接,得到HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方式,连接超时,读取数据超时
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(6000);
//链接服务器
connection.connect();
//发送请求,得到响应数据
int responseCode = connection.getResponseCode();
//必须是200才读
if (responseCode==200) {
//得到InputStream,读取成string
InputStream is = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buffer = new byte[2014];
int len =-1;
while ((len=is.read(buffer))!=-1) {
baos.write(buffer,0,len);
}
final String result = baos.toString();

baos.close();
is.close();
runOnUiThread(new Runnable() {
@Override
public void run() {
et_net_show.setText(result);
dialog.dismiss();
}
});
}

connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
dialog.dismiss();
}
}
}.start();post请求
//显示ProgressDialog
final ProgressDialog dialog = ProgressDialog.show(netActivity.this, null, "正在加载中....");
//启动分线程
new Thread(){
public void run() {
try {
String path = et_net_url.getText().toString(); //得到path
URL url = new URL(path);//创建URL对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();//打开链接,得到HttpURLConnection连接对象
connection.setRequestMethod("POST");//设置请求方式
connection.setConnectTimeout(5000);//设置连接时间
connection.setReadTimeout(5000);//设置读取时间
connection.connect();//打开链接
//发请求,得到响应数据
//得到输出流,写请求体:name=Tom&age=21
OutputStream os = connection.getOutputStream();
String data = "name=哈哈&age=21";
os.write(data.getBytes("utf-8"));
int responseCode = connection.getResponseCode();
if (responseCode==200) {
InputStream is = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2014];
int len=-1;
while ((len=is.read(buffer))!=-1) {
baos.write(buffer,0,len);
}
final String result = baos.toString();
baos.close();
is.close();
runOnUiThread(new Runnable() {
@Override
public void run() {
et_net_show.setText(result);
dialog.dismiss();
}
});
connection.disconnect();

}
os.close();
} catch (Exception e) {
e.printStackTrace();
dialog.dismiss();
}

}

} .start();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: