您的位置:首页 > 移动开发 > Android开发

Android之远程服务器存储

2016-08-03 21:08 85 查看
在使用远程服务器存储时,应先建立一个服务器

一,使用HttpConnection

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

URL(path) : 包含请求路径的构造方法
openConnection() : 得到连接对象

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

setMethod(“GET/POST”) : 设置请求方式
setConnectTimeout(time) : 设置连接超时时间, 单位为ms
setReadTimeout(time): 设置读取服务器返回数据的时间
connect() : 连接服务器
int getResponseCode(): 得到服务器返回的结果码
Int getContentLength() : 得到服务器返回数据的长度(字节)
getOutputStream() : 返回一个指向服务器端的数据输出流
getInputStream() : 返回一个从服务器端返回的数据输入流
disconnect() : 断开连接
/*
* 使用httpUrlConnection提交get请求
*/
/*
1.显示ProgressDialog
2.启动分线程
3.在分线程,发送请求,得到响应数据
1).得到path,并带上参数name=Tom&age=11
2).创建URL对象
3).打开连接,得到HttpURLConnection对象
4).设置请求方式,连接超时,读取数据超时
5).连接服务器
6).发请求,得到响应数据
得到响应码,必须是200才读取
得到InputStream,并读取成String
7).断开连接
4.在主线程,显示得到的结果,移除Dialog
*/
public void testConnectionGet(View v){
//1.显示ProgressDialog
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中。。。");
//2.启动分线程
new Thread(){
//3.在分线程,发送请求,得到响应数据
public void run() {
try {
// 1).得到path,并带上参数name=Tom&age=11
String path = et_network_url.getText().toString()
+ "?name=Tom&age=11";
// 2).创建URL对象
Log.i("TAG", path);
URL url = new URL(path);
Log.i("TAG", "2222");
// 3).打开连接,得到HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 4).设置请求方式,连接超时,读取数据超时
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(6000);
Log.i("TAG", "333");
// 5).连接服务器
connection.connect();
Log.i("TAG", path);
// 6).发请求,得到响应数据
// 得到响应码,必须是200才读取
int responseCode = connection.getResponseCode();
if(responseCode==200){
// 得到InputStream,并读取成String
InputStream is = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
final String result = baos.toString();
baos.close();
is.close();

//4.在主线程,显示得到的结果,移除Dialog
runOnUiThread(new Runnable() {
public void run() {
et_network_result.setText(result);
dialog.dismiss();
}
});
}
//7).断开连接
connection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//如果出了异常要移除Dialog
dialog.dismiss();
}
};
}.start();
}


/*
* 使用httpUrlConnection提交post请求
*/
/*
1.显示ProgressDialog
2.启动分线程
3.在分线程,发送请求,得到响应数据
1).得到path
2).创建URL对象
3).打开连接,得到HttpURLConnection对象
4).设置请求方式,连接超时,读取数据超时
5).连接服务器
6).发请求,得到响应数据
得到输出流,写请求体:name=Tom1&age=11
得到响应码,必须是200才读取
得到InputStream,并读取成String
7).断开连接
4.在主线程,显示得到的结果,移除Dialog
*/
public void testConnectionPost(View v){
//1.显示ProgressDialog
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在加载中。。。");
//2.启动分线程
new Thread(new Runnable() {
//3.在分线程,发送请求,得到响应数据
@Override
public void run() {
try {
// 1).得到path
String path = et_network_url.getText().toString();
// 2).创建URL对象
URL url = new URL(path);
// 3).打开连接,得到HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 4).设置请求方式,连接超时,读取数据超时
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 5).连接服务器
connection.connect();
// 6).发请求,得到响应数据
// 得到输出流,写请求体:name=Tom1&age=11
OutputStream os = connection.getOutputStream();
String data = "name=Tom2&age=12";
os.write(data.getBytes("utf-8"));
// 得到响应码,必须是200才读取
int responseCode = connection.getResponseCode();
if(responseCode==200){
// 得到InputStream,并读取成String
InputStream is = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
final String result = baos.toString();
baos.close();
is.close();

//4.在主线程,显示得到的结果,移除Dialog
runOnUiThread(new Runnable() {
public void run() {
et_network_result.setText(result);
dialog.dismiss();
}
});
}
os.close();
// 7).断开连接
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}).start();

}二,  使用HttpClient
1.HttpClient/DefaultHttpClient : 能提交请求的客户端对象

HttpResponse execute (HttpUriRequest request) 
执行包含请求数据的请求对象, 返回包含响应数据的响应对象
HttpParams getParams()
得到包含请求参数的对象

2.: HttpConnectionParams : 设置请求参数的工具类

static setConnectionTimeout(params, time) : 设置获取连接的超时时间
static setSoTimeout(params, time): 设置读取数据的超时时间

3.HttpGet : Get请求

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

4.HttpPost : Post请求
HttpPost(String path) : 包含请求路径的构造方法
setEntity(HttpEntity entity) : 设置请求体

5.NameValuePair/BasicNameValuePair : 包含参数键值对

BasicNameValuePair (String name, String value) 

6.HttpResponse : 服务器返回的响应
getStatusLine() : 得到响应状态行, 从而得到状态码
getEntity() : 得到响应体数据对象

7.EntityUtils : 解析HttpEntity的工具类
toString(httpEntity):  解析响应体, 得其内容字符串

8.  关闭连接, 释放资源:client.getConnectionManager().shutdown();

/*
* 使用httpClient提交get请求
*/
public void testClientGet(View v){
//1.显示ProgressDialog
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中。。。");
//2.启动分线程
new Thread(){
//3.在分线程,发送请求,得到响应数据
public void run() {
try {
// 1).得到path,并带上参数name=Tom&age=11
String path = et_network_url.getText().toString() + "?name=Tom3&age=13";

//2).创建Client对象
HttpClient httpClient = new DefaultHttpClient();
//3).设置超时
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);

//4).创建请求对象
HttpGet request = new HttpGet(path);
//5).执行请求对象,得到响应对象
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode==200){
//6).得到响应体文本
HttpEntity entity = response.getEntity();
final String result = EntityUtils.toString(entity);
//4.在主线程,显示数据,移除dialog
runOnUiThread(new Runnable() {
public void run() {
et_network_result.setText(result);
dialog.dismiss();
}
});
}
//7).断开连接
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//如果出了异常要移除Dialog
dialog.dismiss();
}
};
}.start();
}
/*
* 使用httpClient提交post请求
*/
public void testClientPost(View v){
//1.显示ProgressDialog
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中。。。");
//2.启动分线程
new Thread(){
//3.在分线程,发送请求,得到响应数据
public void run() {
try {
// 1).得到path
String path = et_network_url.getText().toString();

//2).创建Client对象
HttpClient httpClient = new DefaultHttpClient();
//3).设置超时
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);

//4).创建请求对象
HttpPost request = new HttpPost(path);
//设置请求体
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("name", "Tom4"));
parameters.add(new BasicNameValuePair("age", "14"));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
request.setEntity(entity);
//5).执行请求对象,得到响应对象
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode==200){
//6).得到响应体文本
entity = response.getEntity();
final String result = EntityUtils.toString(entity);
//4.在主线程,显示数据,移除dialog
runOnUiThread(new Runnable() {
public void run() {
et_network_result.setText(result);
dialog.dismiss();
}
});
}
//7).断开连接
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//如果出了异常要移除Dialog
dialog.dismiss();
}
};
}.start();

}


三,Volley

Volley是Google 2013年的 I/O大会 上,发布了的一个框架
Volley是Android上的网络通信库,能使网络通信更快,更简单,更健壮
Volley特别适合数据量不大但是通信频繁的场景: 带图片的列表

1.RequestQueue :  请求队列, 会自动执行队列中的请求

Volley. newRequestQueue(context) : 创建一个请求队列
addReqeust(Request reqeust) : 将请求添加到请求队列

2.Request<T>: 代表请求的接口

StringRequest : 获取字符串结果的请求
JsonRequest : 获取Json数据结果的请求
ImageRequest : 获取图片结果的请求

/*
* 使用Volley提交get请求
*/
/*
1.创建请求队列对象(一次)
2.创建请求对象StringRequest
3.将请求添加到队列中
*/
public void testVolleyGet(View v){
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中。。。");
//创建请求对象StringRequest
String path = et_network_url.getText().toString() + "?name=Tom5&age=15";
StringRequest request = new StringRequest(path, new Response.Listener<String>() {
@Override
public void onResponse(String response) {//在主线程执行
et_network_result.setText(response);
dialog.dismiss();
}
}, null);
//将请求添加到队列中
queue.add(request);
}
/*
* 使用Volley提交post请求
*/
public void testVolleyPost(View v){
final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中。。。");
//创建请求对象StringRequest
String path = et_network_url.getText().toString();
StringRequest request = new StringRequest(Method.POST,path,new Response.Listener<String>() {
@Override
public void onResponse(String response) {
et_network_result.setText(response);
dialog.dismiss();
}
},null){
//重写此方法返回参数的map作为请求体
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String, String>();
map.put("name", "Tom6");
map.put("age", "16");
return map;
}
};
//将请求添加到队列中
queue.add(request);

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