用android 自带的包进行网络请求
16lz
2021-01-25
目的是为了不依赖第三方的jar包进行网络请求(如:commons-httpclient.jar)
1. 建立一个连接配置类
Java代码
2. 封装请求类
Java代码
3. 调用
GET请求
Java代码
Java代码
POST请求
Java代码
1. 建立一个连接配置类
Java代码
- classUserAgentConfig{
- publicStringhost;
- publicStringscheme="http";
- publicintport=80;
- publicinttimeoutConnection=3000;
- publicinttimeoutSocket=20000;
- publicStringusername="";
- publicStringpassword="";
- }
2. 封装请求类
Java代码
- publicclassHttpRequest{
- /**
- *get"Stream"asresponse
- *
- *@paramurlrequestURL
- *@paramconfigconnectionconfig,canbenull
- *@paramparamsparameterforpostmethod,canbenull
- *@returnresponseinstream
- */
- publicstaticInputStreamgetStream(Stringurl,UserAgentConfigconfig,
- List<BasicNameValuePair>params){
- HttpEntityentity=httprequest(url,config,params);
- InputStreamret=null;
- if(entity!=null){
- try{
- byte[]b=EntityUtils.toByteArray(entity);
- ret=newByteArrayInputStream(b);
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- release(entity);
- }
- }
- returnret;
- }
- /**
- *get"String"asresponse
- *
- *@paramurlrequestURL
- *@paramconfigconnectionconfig,canbenull
- *@paramparamsparameterforpostmethod,canbenull
- *@returnresponseinstring
- */
- publicstaticStringgetString(Stringurl,UserAgentConfigconfig,
- List<BasicNameValuePair>params){
- HttpEntityentity=httprequest(url,config,params);
- Stringret=null;
- if(entity!=null){
- try{
- ret=EntityUtils.toString(entity);
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- release(entity);
- }
- }
- returnret;
- }
- privatestaticvoidrelease(HttpEntityentity){
- try{
- entity.consumeContent();
- }catch(IOExceptione){
- e.printStackTrace();
- }
- }
- /**
- *get"HttpEntity"asresponse
- *
- *@paramurlrequestURL
- *@paramconfigconnectionconfig,canbenull
- *@paramparamsparameterforpostmethod,canbenull
- *@return
- */
- privatestaticHttpEntityhttprequest(Stringurl,UserAgentConfigconfig,
- List<BasicNameValuePair>params){
- DefaultHttpClientclient=null;
- HttpEntityentity=null;
- try{
- BasicHttpParamshttpParameters=newBasicHttpParams();
- if(config!=null){
- //setconnectiontimeout
- HttpConnectionParams.setConnectionTimeout(httpParameters,
- config.timeoutConnection);
- HttpConnectionParams.setSoTimeout(httpParameters,
- config.timeoutSocket);
- }
- client=newDefaultHttpClient(httpParameters);
- DefaultHttpRequestRetryHandlerretryHandler=newDefaultHttpRequestRetryHandler(
- 3,true);
- client.setHttpRequestRetryHandler(retryHandler);
- //setusername&passwordifavailable
- if(config!=null
- &&!("".equals(config.username)&&""
- .equals(config.password))){
- AuthScopeas=newAuthScope(config.host,config.port);
- UsernamePasswordCredentialsupc=newUsernamePasswordCredentials(
- config.username,config.password);
- client.getCredentialsProvider().setCredentials(as,upc);
- }
- //checkgetorpostmethodbyparams
- HttpRequestBasemethod=null;
- if(params==null){
- method=newHttpGet(url);
- }else{
- method=newHttpPost(url);
- ((HttpPost)method).setEntity(newUrlEncodedFormEntity(params,
- "utf-8"));
- }
- method.setHeader("Content-Type","application/xml");
- //getresponse
- HttpResponseresponse=null;
- if(config==null){
- //onlyurlisavailable
- response=client.execute(method);
- }else{
- BasicHttpContextlocalContext=newBasicHttpContext();
- BasicSchemebasicAuth=newBasicScheme();
- localContext.setAttribute("preemptive-auth",basicAuth);
- HttpHosttargetHost=newHttpHost(config.host,config.port,
- config.scheme);
- response=client.execute(targetHost,method,localContext);
- }
- entity=response.getEntity();
- }catch(Exceptione){
- e.printStackTrace();
- }
- returnentity;
- }
- }
3. 调用
GET请求
Java代码
- Stringurl="...";
- test(url,null,null);
Java代码
- Stringurl="...";
- UserAgentConfigconfig=newUserAgentConfig();
- config.host="...";
- test(url,config,null);
POST请求
Java代码
- Stringurl="...";
- UserAgentConfigconfig=newUserAgentConfig();
- config.host="...";
- config.username="...";
- config.password="...";
- ArrayList<BasicNameValuePair>params=newArrayList<BasicNameValuePair>();
- params.add(newBasicNameValuePair("...","..."));
- ...
- test(url,config,params);
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- Nginx系列教程(六)| 手把手教你搭建 LNMP 架构并部署天空网络电影
- Android类似于滚动的通知栏实现
- Android性能分析工具Systrace和TraceView,性能测试GT等
- Android中双击返回键退出应用实例代码
- 实现activity全屏显示
- android代码power off 以及特定文件格式的使用
- 如何解决Eclipse中Android(安卓)代码自动补全卡死的问题
- Android网络访问与数据解析