Android网络通信的实现方式
Android网络编程分为两种:基于http协议的,和基于socket的。
基于Http协议:HttpClient、HttpURLConnection、AsyncHttpClient框架等
基于Socket:
(1)针对TCP/IP的Socket、ServerSocket
(2)针对UDP/IP的DatagramSocket、DatagramPackage
(3)ApacheMina框架
一、HttpURLConnection的实现方式
Stringresponse=null; Urlurl=newURL(path); HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//新建连接实例 connection.setConnectTimeout(20000);//设置连接超时时间,单位毫秒 //connection.setReadTimeout(20000);//设置读取数据超时时间,单位毫秒 connection.setDoInput(true);//是否打开输入流true|false connection.setRequestMethod("POST");//提交方法POST|GET //connection.setUseCaches(false);//是否缓存true|false //connection.setRequestProperty("accept","*/*"); //connection.setRequestProperty("Connection","Keep-Alive"); //connection.setRequestProperty("Charset","UTF-8"); //connection.setRequestProperty("Content-Length",String.valueOf(data.length)); //connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); connection.connect();//打开连接端口 intresponseCode=conn.getResponseCode(); BufferedReaderreader=null; if(responseCode==200){ reader=newBufferedReader(newInputStreamReader(connection.getInputStream(),"utf-8")); StringBufferbuffer=newStringBuffer(); Stringline=""; while((line=reader.readLine())!=null){ buffer.append(line); } response=buffer.toString(); }else{ response="返回码:"+responseCode; } reader.close(); conn.disconnect();
二、HttpClient实现方式
HttpResponsemHttpResponse=null; HttpEntitymHttpEntity=null; //创建HttpPost对象 //HttpPosthttppost=newHttpPost(path); //设置httpPost请求参数 //httppost.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8)); HttpGethttpGet=newHttpGet(path); HttpClienthttpClient=newDefaultHttpClient(); InputStreaminputStream=null; BufferedReaderbufReader=null; Stringresult=""; //发送请求并获得响应对象 mHttpResponse=httpClient.execute(httpGet);//如果是“POST”方式就传httppost if(mHttpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ //获得响应的消息实体 mHttpEntity=mHttpResponse.getEntity(); //获取一个输入流 inputStream=mHttpEntity.getContent(); bufReader=newBufferedReader(newInputStreamReader(inputStream)); Stringline=""; while(null!=(line=bufReader.readLine())){ result+=line; } //result=EntityUtils.toString(mHttpResponse.getEntity()); } if(inputStream!=null){ inputStream.close(); } bufReader.close(); if(httpClient!=null){ httpClient.getConnectionManager().shutdown(); }
三、实用AsyncHttpClient框架的实现方式
AsyncHttpClientclient=newAsyncHttpClient(); client.get(url,newAsyncHttpResponseHandler(){ @Override publicvoidonSuccess(inti,Header[]headers,byte[]bytes){ Stringresponse=newString(bytes,0,bytes.length,"UTF-8"); } @Override publicvoidonFailure(inti,Header[]headers,byte[]bytes,Throwablethrowable){ } });
四、使用WebView视图组件显示网页
myWebView.getSettings().setJavaScriptEnabled(true); myWebView.setWebViewClient(newWebViewClient(){ @Override publicbooleanshouldOverrideUrlLoading(WebViewview,Stringurl){ view.loadUrl(url); returntrue; } }); myWebView.loadUrl("http://"+networkAddress);
以上就是Android中网络通信几种方式的全部内容,希望对大家的学习有所帮助。