设为首页 收藏本站
查看: 547|回复: 0

[经验分享] Android(1)-HttpClient(apache)网络访问参考

[复制链接]

尚未签到

发表于 2015-8-3 10:06:31 | 显示全部楼层 |阅读模式
  本文是在android应用上使用apache的HttpClient访问网络-此处工具类代码并未实践,只做参考,具体使用,需要调试
  HttpClient:apache家给android应用提供的的网络访问工具类
  BasicHttpParams:Http访问参数类
  HttpProtocolParams:Http访问参数协议类
  ConnManagerParams:Http访问链接管理类
  HttpConnectionParams:http访问链接参数类
  SchemeRegistry:http访问策划注册类,SchemeRegistry类用来维持一组Scheme
  ClientConnectionManager:http访问用户链接管理, ClientConnectionManager可用来设置访问线程安全,管理持久连接和同步访问持久连接来确保同一时间仅有一个线程可以访问一个连接
  HttpPost:http访问Post请求类
  HttpGet:http访问Get请求类
  HttpResponse:http访问回应
  HttpEntity:http访问数据实体,用来封装访问的数据,通过setEntity()传入httpPost或httpHost,同时会从HttpResponse放回该种数据实体;
  同时,官方提供了个中对HttpEntity的封装使用,如下:参考链接:http://my.oschina.net/u/1046089/blog?disp=2&p=1


  • BasicHttpEntity
  • ByteArrayEntity
  • StringEntity
  • InputStreamEntity
  • FileEntity
  • EntityTemplate
  • HttpEntityWrapper
  • BufferedHttpEntity
  WARNING: 在http访问链接结束是记得释放链接 entity.consumeContent();
  以下是源码类:
  OwnHttpClient.java



package com.example.testhttpclient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
public class OwnHttpClient {
private static final int POOL_TIMEOUT = 20 * 1000;// 设置连接池超时20秒钟
private static final int REQUEST_TIMEOUT = 5 * 1000;// 设置请求超时5秒钟
private static final int REQUEST_WIFI_TIMEOUT = 10 * 1000;// 设置请求超时10秒钟
private static final int SO_TIMEOUT = 5 * 1000; // 设置等待数据超时时间5秒钟
private static OwnHttpClient instance;
private DefaultHttpClient httpClient;    //DefaultHttpClient是实现HttpClient接口的子类
private Context context;                //获取想取得该OwnHttpClient的的环境(Activity.this)
private static String urlBasePath = "http://www.myhome.cn/oa";
private String TAG = OwnHttpClient.class.getSimpleName();
//构造函数中获取httpClient
private OwnHttpClient(Context context) {
this.context = context;
this.httpClient = getHttpClient();
}
//Singleton
public static OwnHttpClient getInstance(Context context) {
if(instance == null) {
synchronized (OwnHttpClient.class) {
instance = new OwnHttpClient(context);
}   
}
return instance;
}
//获取HttpClient
public DefaultHttpClient getHttpClient() {
if (null == httpClient) {
// 设置一些基本参数
BasicHttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
HttpProtocolParams.setUseExpectContinue(httpParams, true);
HttpProtocolParams
.setUserAgent(
httpParams,
"Mozilla/5.0(Linux;U;Android 2.3.3;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 代理的设置
HttpHost proxy = new HttpHost("10.60.8.20", 8080);
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(httpParams, POOL_TIMEOUT); // 设置连接池超时0秒钟
if(NetManager.isWifiDataEnable((Activity)context)) {    //自定义类NetManager,判断是否为wifi请求,并 设置请求超时0秒钟
                HttpConnectionParams.setConnectionTimeout(httpParams,   
REQUEST_WIFI_TIMEOUT);   
} else {
HttpConnectionParams.setConnectionTimeout(httpParams,
REQUEST_TIMEOUT);  
}
HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT); // 设置等待数据超时时间0秒钟
// 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
httpParams, schReg);
httpClient = new DefaultHttpClient(conMgr, httpParams);
//httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));
        }
return httpClient;
}
/**
* make the connection of post
* post request start-----------------------
*/
//------normal post---------
public String post(String url, NameValuePair... nameValuePairs) {
return post(url, null, nameValuePairs);
}
public String post(String url, List headers, NameValuePair... nameValuePairs) {
url = OwnHttpClient.urlBasePath + url;
//参数(nameValuePairs)不为null,转换成list数组
List formParams = new ArrayList();
if(nameValuePairs != null) {                           
for(NameValuePair param:nameValuePairs) {
formParams.add(param);
}
}
HttpPost httpPost = null;
HttpResponse response = null;
HttpEntity entity = null;   //BasicHttpEntity这类就是一个输入流的内容包装类,包装内容的相关的编码格式,长度等
try {
httpPost = getHttpPost(url, headers);        //获取HttpPost请求
httpPost.setEntity(new UrlEncodedFormEntity(formParams, HTTP.UTF_8));    //传入entity,设置参数传输
response = httpClient.execute(httpPost);    //用HttpClient发送post请求
entity = response.getEntity();                //获取post请求放回的数据
            
StatusLine sl = response.getStatusLine();    //获取post他请求返回的状态行StatusLine
if(sl.getStatusCode() == HttpStatus.SC_OK)    //获取状态行中的状态Code,并判断是否为SC_OK(200)
return EntityUtils.toString(entity);    //为SC_OK这该post方法返回获取到的entity数据
} catch(UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Log.e(TAG, "UnsupportedEncodingException: " + e.getMessage());
} catch(ClientProtocolException e) {
// TODO Auto-generated catch block
Log.e(TAG, "ClientProtocolException: " + e.getMessage());
} catch(IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IOException: " + e.getMessage());
} finally {
if(entity != null) {
try {
entity.consumeContent();            // 释放连接(关闭流)
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IOException: " + e.getMessage());
}
}
}
return "";
}
//--------post as stream-----------
public String postAsStream(String url, String strEntity) {
return postAsStream(url, null, strEntity);
}
public String postAsStream(String url, List headers, String strEntity) {
url = OwnHttpClient.urlBasePath + url;
HttpPost httpPost = null;
HttpResponse response = null;
HttpEntity entity = null;
try {
httpPost = getHttpPost(url, headers);                 //获取HttpPost请求
StringEntity se = new StringEntity(strEntity);   
//HttpEntityWrapper是创建包装实体的基类。,具体实现在实体类中操作,如ContentHttpEntity
//BufferedHttpEntity是HttpEntityWrapper的子类
//自定义封装HttpEntityWrapper
ContentHttpEntity che = new ContentHttpEntity(se);        
httpPost.setEntity(che);                            //传入entity,设置参数传输
response = httpClient.execute(httpPost);            //用HttpClient发送post请求
entity = response.getEntity();                        //获取post请求放回的数据
            
StatusLine sl = response.getStatusLine();            //获取pos他请求返回的状态行StatusLine
if(sl.getStatusCode() == HttpStatus.SC_OK)             //获取状态行中的状态Code,并判断是否为SC_OK(200)
return EntityUtils.toString(entity);            //为SC_OK这该post方法返回获取到的entity数据
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Log.e(TAG, "UnsupportedEncodingException: " + e.getMessage());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.e(TAG, "ClientProtocolException: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IOException: " + e.getMessage());
} finally {
if(entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
}
}
}
return "";
}
//get HttpPost
private HttpPost getHttpPost(String url, List headers) {
HttpPost httpPost = new HttpPost(url);
if(headers != null) {
for(Header header:headers) {
httpPost.setHeader(header);
}
}
return httpPost;
}
//--------post request end------------------------
/**
* make the connection of post
* post request start
*/
//    public String get(String url) {
//        return get(url, null);
//    }
public String get(String url, NameValuePair... nameValuePairs) {
return get(url, null, nameValuePairs);
}
public String get(String url, List headers, NameValuePair... nameValuePairs) {
url = OwnHttpClient.urlBasePath + url;
StringBuffer sb = new StringBuffer();
sb.append(url);
if(nameValuePairs != null && nameValuePairs.length>0) {
for(int i=0;i 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
nameValuePairs.getName(),nameValuePairs.getValue()));
}
}
//
        HttpGet httpGet = null;
HttpResponse response = null;
HttpEntity entity = null;     //BasicHttpEntity这类就是一个输入流的内容包装类,包装内容的相关的编码格式,长度等
try {
httpGet = getHttpGet(sb.toString(), headers);                //获取get请求
response = httpClient.execute(httpGet);            //用HttpClient发送httpGet请求
entity = response.getEntity();                    //获取response放回去的数据
            
StatusLine sl = response.getStatusLine();        //获取response返回的状态行
if(sl.getStatusCode() == HttpStatus.SC_OK)        //获取状态行中的状态码,并判断是否为SC_OK(200)
return EntityUtils.toString(entity);        //如果请求正常,该方法返回entity中的数据
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.e(TAG, "ClientProtocolException: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IOException: " + e.getMessage());
} finally {
if(entity != null) {                            //到最后不要忘了释放链接,关闭流
try {
entity.consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
}
}
}
return "";
}
//get HttpGet
private HttpGet getHttpGet(String url, List headers) {
HttpGet httpGet = new HttpGet();
if(headers != null) {
for(Header header:headers) {
httpGet.setHeader(header);
}
}
return httpGet;
}
//----get request end---------------
/*
* cookie
*/
public void clearCookie() {
httpClient.getCookieStore().clear();    //清除cookie
    }
}
  
  ContentHttpEntity.java
  轻量封装HttpEntityWrapper,被OwnHttpClient.java调用



package com.example.testhttpclient;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
public class ContentHttpEntity extends HttpEntityWrapper {
public ContentHttpEntity(HttpEntity wrapped) {
super(wrapped);
// TODO Auto-generated constructor stub
    }
@Override
public void writeTo(OutputStream outstream) throws IOException {
// TODO Auto-generated method stub
this.wrappedEntity.writeTo(outstream instanceof ContentOutStream ? outstream : new ContentOutStream(outstream));
}
static class ContentOutStream extends FilterOutputStream {
public ContentOutStream(final OutputStream outstream) {
super(outstream);
// TODO Auto-generated constructor stub
        }
@Override
public void write(byte[] buffer, int offset, int length)
throws IOException {
// TODO Auto-generated method stub
super.write(buffer, offset, length);
}
@Override
public void write(byte[] buffer) throws IOException {
// TODO Auto-generated method stub
super.write(buffer);
}
}
}
  
  NetManager.java
  自定网络管理类,此次用于判断是否使用wifi,被OwnHttpClient.java调用



package com.example.testhttpclient;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
public class NetManager {
public static boolean isWifiDataEnable(Activity activity) {
WifiManager wifiManager =
(WifiManager)activity.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
if(wifiManager.isWifiEnabled() && ipAddress != 0) {
return true;
} else {
return true;
}
}
}
  
  本例子原型:https://github.com/eoecn/android-app/blob/master/source/src/cn/eoe/app/https/CustomHttpClient.java
  学习参考:http://www.iyunv.com/loveyakamoz/archive/2011/07/21/2112832.html
  学习参考:http://my.oschina.net/u/1046089/blog?disp=2&p=1
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-93577-1-1.html 上篇帖子: Apache配置文件属性、参数的含义 下篇帖子: httpd: apr_sockaddr_info_get() failed for apache 启动问题
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表