Android网络编程核心技术(一)Apache接口
2017-02-26 20:50
393 查看
在Android系统中,提供了如下3种通信接口:
Apache接口:org.apache.http。
标准Java接口:java.net。
Android网络接口:android.net.http。
1.使用Apache接口
在Android系统中,可以采用HttpPost和HttpGet封装post和Get请求,再使用HttpClient的excute()方法发送post()或者get()请求,并返回服务器的响应数据。
对于post和get的区别推荐下面链接的文章,个人觉得讲的中肯也很深入,http://www.techweb.com.cn/network/system/2016-10-11/2407736.shtml
基本流程可以参照下面的代码:
1.1实现Get请求
(1)得到网页HTML代码
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(网址);
// String response = httpClient.excute(get);
HttpReponse response = httpClient.excute(get);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer line = reader.readLine();
while(line!=null){
line.append(line) ;
line =
reader.readLine();
}
}catch...
(2)简单Get请求得到网页响应结果,转化为字符串
try{
HttpClient httpClient = new DefaultHttpClient(httpParams);
HttpGet get = new HttpGet(网址);
String response = httpClient.excute(get,new BasicResponseHandler());
}catch...
(3) 提交带表单的url,百度搜索常出现,如www.baidu.com/s?ie=utf-8&tn=baidu&wd=csdn,获取到输入流(服务器指定)转化为字符串
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(带表单的url);
HttpReponse response = httpClient.excute(get);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)){
InputStream is = response.getEntity().getContent();
String result = StreamToString(is);
}
}catch...
//不了解流的读者可以先预览一下java的输入输出
private String StreamToString(InputStream is) throws Exception{
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = is.read(bytes);//由is到bytes,每次最多读取1024个字节,len是读取的长度
while(len!=-1){
byteStream.write(bytes,0,len);//由bytes到 byteStream
len = is.read(bytes);
}
return new String(byteStream.toByteArray());//带参数的String
}
1.2 实现post请求
使用post的url后面并没有带有提交内容的表单,而是被包装成了一个NmaeValuePari的类型的集合形式,然后调用HttpPost的setEntity设置参数,最后由HttpClient执行。
1.3 实现文件上传
在有些场合例如我们需要用到上传文件的时候,就不能使用基本的get和post请求了,下面介绍一个使用多部件Post上传文件到服务器。首先需要到Apache官网下载HttpComponent,把其中的HttpMine.jar放到项目中。
我们用HttpMine提供的InputStreamBody处理文件流,用StringBody处理简单的文本,最后把他们都放入MultipartEntity的实体中,然后将这个MultipartEntity设为post的参数实体,再执行post。
public void upLoad() throws Exception{
InputStream is = getContext().getAssets().open("book.xml");//注意getContext().getAssets()取得的是当前路径
HttpClient client = new DefaultClient();
HttpPost post = new HttpPost(url);
InputStreamBody streamBody = new InputStreamBody(is,"book.xml");
MultipartEntity multientity = new MultipartEntity();
multientity.addPart("file",streamBody);
multientity.addPart("desc","fileupload is so easy to study");
post.setEntity(multientity);
HttpReponse response = httpClient.excute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)){
is = response.getEntity().getContent();
String result = StreamToString(is);
}
从上面的代码中可以看出,在发送get请求时参数放在Url中即可,也可以没有参数,发送post请求时将参数封装成Entity实体再发送。不管post还是get请求,如果程序返回的确定是字符流,则可以用字符流来读取,否则健壮一点的代码还是使用字节流读取。
1.4 多线程
在很多Android项目中,需要在多处进行Http通信,这时显然为每个请求创建一个新的HttpClient是不明智的,反而整个应用使用一个HttpClient就够了。通过一个HttpClient同时发出多个请求时可能引起多线程问题,处理过程如下:
(1)扩展系统默认的MyApplication,并应用到项目中
pubilc void onCreate(){
super.onCreate();
httpclient = this.createHttpClient();
}
//关闭连接管理器,看情况调用
private void shutdownHttpClient(){
if(httpclient!=null&&httpclient.getConnectioonManager()!=null){
httpclient.getConnectioonManager().shutdown();
}
}
//对外提供HttpClient实例、
public HttpClient getHttpClient(){
return httpclient;
}
//创建HttpClient实例
public HttpClient createHttpClient(){
HttpParams httpParams = new BasicHttpParams();
......//设置一些版本,编码参数
SchemeRegistry schReg = new SchemeRegistry();
....//继续设置参数,重点在下面两句
CilentConnectionManager connManager = new ThreadSafeClientConnManager(params,schReg);
return new DefaultHttpClient(connManager,params);
}
(2)在Activity中使用
try{
MyApplication app = (MyApplication)this.getApplication();
HttpClient client = app.getHttpClient();
.....//下面常规的写法,上面已有范例
}catch...
Apache接口:org.apache.http。
标准Java接口:java.net。
Android网络接口:android.net.http。
1.使用Apache接口
在Android系统中,可以采用HttpPost和HttpGet封装post和Get请求,再使用HttpClient的excute()方法发送post()或者get()请求,并返回服务器的响应数据。
对于post和get的区别推荐下面链接的文章,个人觉得讲的中肯也很深入,http://www.techweb.com.cn/network/system/2016-10-11/2407736.shtml
基本流程可以参照下面的代码:
1.1实现Get请求
(1)得到网页HTML代码
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(网址);
// String response = httpClient.excute(get);
HttpReponse response = httpClient.excute(get);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer line = reader.readLine();
while(line!=null){
line.append(line) ;
line =
reader.readLine();
}
}catch...
(2)简单Get请求得到网页响应结果,转化为字符串
try{
HttpClient httpClient = new DefaultHttpClient(httpParams);
HttpGet get = new HttpGet(网址);
String response = httpClient.excute(get,new BasicResponseHandler());
}catch...
(3) 提交带表单的url,百度搜索常出现,如www.baidu.com/s?ie=utf-8&tn=baidu&wd=csdn,获取到输入流(服务器指定)转化为字符串
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(带表单的url);
HttpReponse response = httpClient.excute(get);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)){
InputStream is = response.getEntity().getContent();
String result = StreamToString(is);
}
}catch...
//不了解流的读者可以先预览一下java的输入输出
private String StreamToString(InputStream is) throws Exception{
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = is.read(bytes);//由is到bytes,每次最多读取1024个字节,len是读取的长度
while(len!=-1){
byteStream.write(bytes,0,len);//由bytes到 byteStream
len = is.read(bytes);
}
return new String(byteStream.toByteArray());//带参数的String
}
1.2 实现post请求
使用post的url后面并没有带有提交内容的表单,而是被包装成了一个NmaeValuePari的类型的集合形式,然后调用HttpPost的setEntity设置参数,最后由HttpClient执行。
List<NameValueP ccfe air> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("id",id));
。。。。//对params调用add添加数据
try { HttpPost request = new HttpPost(url); HttpResponse response; HttpClient httpClient = new DefaultHttpClient(); try{ HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); request.setEntity(entity); response = httpClient.execute(request); //如果返回状态为200,获得返回的结果 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { str = EntityUtils.toString(response.getEntity()); } }catch (Exception e){ e.printStackTrace(); } }catch(Exception e){ e.printStackTrace(); }
1.3 实现文件上传
在有些场合例如我们需要用到上传文件的时候,就不能使用基本的get和post请求了,下面介绍一个使用多部件Post上传文件到服务器。首先需要到Apache官网下载HttpComponent,把其中的HttpMine.jar放到项目中。
我们用HttpMine提供的InputStreamBody处理文件流,用StringBody处理简单的文本,最后把他们都放入MultipartEntity的实体中,然后将这个MultipartEntity设为post的参数实体,再执行post。
public void upLoad() throws Exception{
InputStream is = getContext().getAssets().open("book.xml");//注意getContext().getAssets()取得的是当前路径
HttpClient client = new DefaultClient();
HttpPost post = new HttpPost(url);
InputStreamBody streamBody = new InputStreamBody(is,"book.xml");
MultipartEntity multientity = new MultipartEntity();
multientity.addPart("file",streamBody);
multientity.addPart("desc","fileupload is so easy to study");
post.setEntity(multientity);
HttpReponse response = httpClient.excute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)){
is = response.getEntity().getContent();
String result = StreamToString(is);
}
从上面的代码中可以看出,在发送get请求时参数放在Url中即可,也可以没有参数,发送post请求时将参数封装成Entity实体再发送。不管post还是get请求,如果程序返回的确定是字符流,则可以用字符流来读取,否则健壮一点的代码还是使用字节流读取。
1.4 多线程
在很多Android项目中,需要在多处进行Http通信,这时显然为每个请求创建一个新的HttpClient是不明智的,反而整个应用使用一个HttpClient就够了。通过一个HttpClient同时发出多个请求时可能引起多线程问题,处理过程如下:
(1)扩展系统默认的MyApplication,并应用到项目中
pubilc void onCreate(){
super.onCreate();
httpclient = this.createHttpClient();
}
//关闭连接管理器,看情况调用
private void shutdownHttpClient(){
if(httpclient!=null&&httpclient.getConnectioonManager()!=null){
httpclient.getConnectioonManager().shutdown();
}
}
//对外提供HttpClient实例、
public HttpClient getHttpClient(){
return httpclient;
}
//创建HttpClient实例
public HttpClient createHttpClient(){
HttpParams httpParams = new BasicHttpParams();
......//设置一些版本,编码参数
SchemeRegistry schReg = new SchemeRegistry();
....//继续设置参数,重点在下面两句
CilentConnectionManager connManager = new ThreadSafeClientConnManager(params,schReg);
return new DefaultHttpClient(connManager,params);
}
(2)在Activity中使用
try{
MyApplication app = (MyApplication)this.getApplication();
HttpClient client = app.getHttpClient();
.....//下面常规的写法,上面已有范例
}catch...
相关文章推荐
- Android网络编程核心技术(二)Java接口和Android接口
- Android网络编程之Apache接口
- Android 网络编程 API笔记 - java.net 包相关 接口 api
- Android网络编程之一:用SAX技术解析XML文件
- 核心技术篇:3.android网络编程之dom解析xml
- 【Android核心基础05】 - 网络编程
- 深入理解Android网络编程:技术详解与最佳实践pdf
- Android学习笔记之网络接口(Http接口,Apache接口,Android接口)
- Java高手真经. 编程基础卷:Java核心编程技术:Java基础+核心库+图形+网络+高级特性
- java 网络 socket编程 Java核心技术读书笔记
- Android通过HttpURLConnection和HttpClient接口实现网络编程
- 核心技术篇:6.android网络编程之json解析
- android网络编程之Apache——HttpClient(淘汰了?)
- Android 的网络编程(3)-HttpURLConnection接口
- Android学习笔记之网络接口(Http接口,Apache接口,Android接口)
- Android 网络编程 API笔记 - java.net 包相关 接口 api
- Android线程—多线程编程核心技术
- Android学习笔记之网络接口(Http接口,Apache接口,Android接口)
- Android学习笔记之网络接口(Http接口,Apache接口,Android接口)
- Android 的网络编程(4)-HttpClient接口