加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

使用单例模式实现的HttpClient工具类

发布时间:2020-05-28 21:07:55 所属栏目:Java 来源:互联网
导读:使用单例模式实现的HttpClient工具类

下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。

脚本之家小编现在分享给大家,也给大家做个参考。

引子

try{
//创建一个默认的HttpClient
HttpClienthttpclient=newDefaultHttpClient();
//创建一个GET请求
HttpGetrequest=newHttpGet("www.google.com");
//发送GET请求,并将响应内容转换成字符串
Stringresponse=httpclient.execute(request,newBasicResponseHandler());
Log.v("responsetext",response);
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}

为什么要使用单例HttpClient?

HttpClienthttpclient=newDefaultHttpClient();
publicclassCustomerHttpClient{
privatestaticHttpClientcustomerHttpClient;

privateCustomerHttpClient(){
}

publicstaticHttpClientgetHttpClient(){
if(null==customerHttpClient){
customerHttpClient=newDefaultHttpClient();
}
returncustomerHttpClient;
}
}
publicclassCustomerHttpClient{
privatestaticfinalStringCHARSET=HTTP.UTF_8;
privatestaticHttpClientcustomerHttpClient;

privateCustomerHttpClient(){
}

publicstaticsynchronizedHttpClientgetHttpClient(){
if(null==customerHttpClient){
HttpParamsparams=newBasicHttpParams();
//设置一些基本参数
HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,CHARSET);
HttpProtocolParams.setUseExpectContinue(params,true);
HttpProtocolParams
.setUserAgent(
params,"Mozilla/5.0(Linux;U;Android2.2.1;en-us;NexusOneBuild.FRG83)"
+"AppleWebKit/553.1(KHTML,likeGecko)Version/4.0MobileSafari/533.1");
//超时设置
/*从连接池中取连接的超时时间*/
ConnManagerParams.setTimeout(params,1000);
/*连接超时*/
HttpConnectionParams.setConnectionTimeout(params,2000);
/*请求超时*/
HttpConnectionParams.setSoTimeout(params,4000);

//设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistryschReg=newSchemeRegistry();
schReg.register(newScheme("http",PlainSocketFactory
.getSocketFactory(),80));
schReg.register(newScheme("https",SSLSocketFactory
.getSocketFactory(),443));

//使用线程安全的连接管理来创建HttpClient
ClientConnectionManagerconMgr=newThreadSafeClientConnManager(
params,schReg);
customerHttpClient=newDefaultHttpClient(conMgr,params);
}
returncustomerHttpClient;
}
}

HttpClient的3种超时说明

/*从连接池中取连接的超时时间*/
ConnManagerParams.setTimeout(params,1000);
/*连接超时*/
HttpConnectionParams.setConnectionTimeout(params,2000);
/*请求超时*/
HttpConnectionParams.setSoTimeout(params,4000);

封装简单的POST请求

privatestaticfinalStringTAG="CustomerHttpClient";

publicstaticStringpost(Stringurl,NameValuePair...params){
try{
//编码参数
List<NameValuePair>formparams=newArrayList<NameValuePair>();//请求参数
for(NameValuePairp:params){
formparams.add(p);
}
UrlEncodedFormEntityentity=newUrlEncodedFormEntity(formparams,CHARSET);
//创建POST请求
HttpPostrequest=newHttpPost(url);
request.setEntity(entity);
//发送请求
HttpClientclient=getHttpClient();
HttpResponseresponse=client.execute(request);
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
thrownewRuntimeException("请求失败");
}
HttpEntityresEntity=response.getEntity();
return(resEntity==null)?null:EntityUtils.toString(resEntity,CHARSET);
}catch(UnsupportedEncodingExceptione){
Log.w(TAG,e.getMessage());
returnnull;
}catch(ClientProtocolExceptione){
Log.w(TAG,e.getMessage());
returnnull;
}catch(IOExceptione){
thrownewRuntimeException("连接失败",e);
}

}

使用我们的CustomerHttpClient工具类

finalStringurl="http://yourdomain/context/adduser";
//准备数据
NameValuePairparam1=newBasicNameValuePair("username","张三");
NameValuePairparam2=newBasicNameValuePair("password","123456");
intresultId=-1;
try{
//使用工具类直接发出POST请求,服务器返回json数据,比如"{userid:12}"
Stringresponse=CustomerHttpClient.post(url,param1,param2);
JSONObjectroot=newJSONObject(response);
resultId=Integer.parseInt(root.getString("userid"));
Log.i(TAG,"新用户ID:"+resultId);
}catch(RuntimeExceptione){
//请求失败或者连接失败
Log.w(TAG,e.getMessage());
Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT);
}catch(Exceptione){
//JSon解析出错
Log.w(TAG,e.getMessage());
}

结语

以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读