使用单例模式实现的HttpClient工具类
发布时间:2020-12-14 23:29:13 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 引子 try?{????????//?创建一个默认的HttpClient????????HttpClient?httpclient?=new?DefaultHttpClient();????????//?创建一个GET请求????????HttpGe
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 引子try?{ ????????//?创建一个默认的HttpClient ????????HttpClient?httpclient?=new?DefaultHttpClient(); ????????//?创建一个GET请求 ????????HttpGet?request?=new?HttpGet("www.google.com"); ????????//?发送GET请求,并将响应内容转换成字符串 ????????String?response?=?httpclient.execute(request,?new?BasicResponseHandler()); ????????Log.v("response?text",?response); ????}?catch?(ClientProtocolException?e)?{ ????????e.printStackTrace(); ????}?catch?(IOException?e)?{ ????????e.printStackTrace(); ????} 为什么要使用单例HttpClient?HttpClient?httpclient?=new?DefaultHttpClient(); publicclass?CustomerHttpClient?{ ????privatestatic?HttpClient?customerHttpClient; ???? ????private?CustomerHttpClient()?{ ????} ???? ????publicstatic?HttpClient?getHttpClient()?{ ????????if(null==?customerHttpClient)?{ ????????????customerHttpClient?=new?DefaultHttpClient(); ????????} ????????return?customerHttpClient; ????} } public?class?CustomerHttpClient?{ ????private?staticfinal?String?CHARSET?=?HTTP.UTF_8; ????private?static?HttpClient?customerHttpClient; ????private?CustomerHttpClient()?{ ????} ????public?static?synchronized?HttpClient?getHttpClient()?{ ????????if?(null==?customerHttpClient)?{ ????????????HttpParams?params?=new?BasicHttpParams(); ????????????//?设置一些基本参数 ????????????HttpProtocolParams.setVersion(params,?HttpVersion.HTTP_1_1); ????????????HttpProtocolParams.setContentCharset(params,????????????????????CHARSET); ????????????HttpProtocolParams.setUseExpectContinue(params,?true); ????????????HttpProtocolParams ????????????????????.setUserAgent( ????????????????????????????params,????????????????????????????"Mozilla/5.0(Linux;U;Android?2.2.1;en-us;Nexus?One?Build.FRG83)?" ????????????????????????????????????+"AppleWebKit/553.1(KHTML,like?Gecko)?Version/4.0?Mobile?Safari/533.1"); ????????????//?超时设置 /*?从连接池中取连接的超时时间?*/ ????????????ConnManagerParams.setTimeout(params,?1000); ????????????/*?连接超时?*/ ????????????HttpConnectionParams.setConnectionTimeout(params,?2000); ????????????/*?请求超时?*/ ????????????HttpConnectionParams.setSoTimeout(params,?4000); ???????????? ????????????//?设置我们的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( ????????????????????params,?schReg); ????????????customerHttpClient?=new?DefaultHttpClient(conMgr,?params); ????????} ????????return?customerHttpClient; ????} } HttpClient的3种超时说明/*?从连接池中取连接的超时时间?*/ ConnManagerParams.setTimeout(params,?1000); /*?连接超时?*/ HttpConnectionParams.setConnectionTimeout(params,?2000); /*?请求超时?*/ HttpConnectionParams.setSoTimeout(params,?4000); 封装简单的POST请求privatestaticfinal?String?TAG?="CustomerHttpClient"; publicstatic?String?post(String?url,?NameValuePair...?params)?{ ????????try?{ ????????????//?编码参数 ????????????List<NameValuePair>?formparams?=new?ArrayList<NameValuePair>();?//?请求参数 for?(NameValuePair?p?:?params)?{ ????????????????formparams.add(p); ????????????} ????????????UrlEncodedFormEntity?entity?=new?UrlEncodedFormEntity(formparams,????????????????????CHARSET); ????????????//?创建POST请求 ????????????HttpPost?request?=new?HttpPost(url); ????????????request.setEntity(entity); ????????????//?发送请求 ????????????HttpClient?client?=?getHttpClient(); ????????????HttpResponse?response?=?client.execute(request); ????????????if(response.getStatusLine().getStatusCode()?!=?HttpStatus.SC_OK)?{ ????????????????thrownew?RuntimeException("请求失败"); ????????????} ????????????HttpEntity?resEntity?=??response.getEntity(); ????????????return?(resEntity?==null)??null?:?EntityUtils.toString(resEntity,?CHARSET); ????????}?catch?(UnsupportedEncodingException?e)?{ ????????????Log.w(TAG,?e.getMessage()); ????????????returnnull; ????????}?catch?(ClientProtocolException?e)?{ ????????????Log.w(TAG,?e.getMessage()); ????????????returnnull; ????????}?catch?(IOException?e)?{ ????????????thrownew?RuntimeException("连接失败",?e); ????????} ????} 使用我们的CustomerHttpClient工具类final?String?url?="http://yourdomain/context/adduser"; ????//准备数据 ????NameValuePair?param1?=new?BasicNameValuePair("username",?"张三"); ????NameValuePair?param2?=new?BasicNameValuePair("password",?"123456"); ????int?resultId?=-1; ????try?{ ????????//?使用工具类直接发出POST请求,服务器返回json数据,比如"{userid:12}" ????????String?response?=?CustomerHttpClient.post(url,?param1,?param2); ????????JSONObject?root?=new?JSONObject(response); ????????resultId?=?Integer.parseInt(root.getString("userid")); ????????Log.i(TAG,?"新用户ID:"+?resultId); ????}?catch?(RuntimeException?e)?{ ????????//?请求失败或者连接失败 ????????Log.w(TAG,?e.getMessage()); ????????Toast.makeText(this,?e.getMessage(),?Toast.LENGTH_SHORT); ????}?catch?(Exception?e)?{ ????????//?JSon解析出错 ????????Log.w(TAG,?e.getMessage()); ????} 结语以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 详解Java多线程编程中CountDownLatch阻塞线程的方法
- Intellij IDEA 2017新特性之Spring Boot相关特征介绍
- java – Spring Boot REST Controller在外部tomcat 9服务器
- java – 为什么在使用repaint()而不是getParent()时会出现这
- java – 航空票价比较网络应用程序如何从多家航空公司获得机
- Java中private、protected、public和default的区别
- java – 如何在MySQL中存储图片?
- java – 基于正则表达式替换的效率
- java – JAXB中属性的AccessOrder
- 在Java中查找调用Method