android网络编程之网络通信几种方式实例分享
如今,手机应用渗透到各行各业,数量难以计数,其中大多数应用都会使用到网络,与服务器的交互势不可挡,那么android当中访问网络有哪些方式呢?
现在总结了六种方式:
(1)针对TCP/IP的Socket、ServerSocket
(2)针对UDP的DatagramSocket、DatagramPackage。这里需要注意的是,考虑到Android设备通常是手持终端,IP都是随着上网进行分配的。不是固定的。因此开发也是有一点与普通互联网应用有所差异的。
(3)针对直接URL的HttpURLConnection。
(4)Google集成了ApacheHTTP客户端,可使用HTTP进行网络编程。
(5)使用WebService。Android可以通过开源包如jackson去支持Xmlrpc和Jsonrpc,另外也可以用Ksoap2去实现Webservice。
(6)直接使用WebView视图组件显示网页。基于WebView进行开发,Google已经提供了一个基于chrome-lite的Web浏览器,直接就可以进行上网浏览网页。
一、socket与serverSocket
客户端代码
publicclassTestNetworkActivityextendsActivityimplementsOnClickListener{
privateButtonconnectBtn;
privateButtonsendBtn;
privateTextViewshowView;
privateEditTextmsgText;
privateSocketsocket;
privateHandlerhandler;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.test_network_main);
connectBtn=(Button)findViewById(R.id.test_network_main_btn_connect);
sendBtn=(Button)findViewById(R.id.test_network_main_btn_send);
showView=(TextView)findViewById(R.id.test_network_main_tv_show);
msgText=(EditText)findViewById(R.id.test_network_main_et_msg);
connectBtn.setOnClickListener(this);
sendBtn.setOnClickListener(this);
handler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
super.handleMessage(msg);
Stringdata=msg.getData().getString("msg");
showView.setText("来自服务器的消息:"+data);
}
};
}
@Override
publicvoidonClick(Viewv){
//连接服务器
if(v==connectBtn){
connectServer();
}
//发送消息
if(v==sendBtn){
Stringmsg=msgText.getText().toString();
send(msg);
}
}
/**
*连接服务器的方法
*/
publicvoidconnectServer(){
try{
socket=newSocket("192.168.1.100",4000);
System.out.println("连接服务器成功");
recevie();
}catch(Exceptione){
System.out.println("连接服务器失败"+e);
e.printStackTrace();
}
}
/**
*发送消息的方法
*/
publicvoidsend(Stringmsg){
try{
PrintStreamps=newPrintStream(socket.getOutputStream());
ps.println(msg);
ps.flush();
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*读取服务器传回的方法
*/
publicvoidrecevie(){
newThread(){
publicvoidrun(){
while(true){
try{
InputStreamis=socket.getInputStream();
BufferedReaderbr=newBufferedReader(newInputStreamReader(is));
Stringstr=br.readLine();
Messagemessage=newMessage();
Bundlebundle=newBundle();
bundle.putString("msg",str);
message.setData(bundle);
handler.sendMessage(message);
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}.start();
}
}
二、RUL、URLConnection、httpURLConnection、ApacheHttp、WebView
publicclassTestURLActivityextendsActivityimplementsOnClickListener{
privateButtonconnectBtn;
privateButtonurlConnectionBtn;
privateButtonhttpUrlConnectionBtn;
privateButtonhttpClientBtn;
privateImageViewshowImageView;
privateTextViewshowTextView;
privateWebViewwebView;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.test_url_main);
connectBtn=(Button)findViewById(R.id.test_url_main_btn_connect);
urlConnectionBtn=(Button)findViewById(R.id.test_url_main_btn_urlconnection);
httpUrlConnectionBtn=(Button)findViewById(R.id.test_url_main_btn_httpurlconnection);
httpClientBtn=(Button)findViewById(R.id.test_url_main_btn_httpclient);
showImageView=(ImageView)findViewById(R.id.test_url_main_iv_show);
showTextView=(TextView)findViewById(R.id.test_url_main_tv_show);
webView=(WebView)findViewById(R.id.test_url_main_wv);
connectBtn.setOnClickListener(this);
urlConnectionBtn.setOnClickListener(this);
httpUrlConnectionBtn.setOnClickListener(this);
httpClientBtn.setOnClickListener(this);
}
@Override
publicvoidonClick(Viewv){
//直接使用URL对象进行连接
if(v==connectBtn){
try{
URLurl=newURL("http://192.168.1.100:8080/myweb/image.jpg");
InputStreamis=url.openStream();
Bitmapbitmap=BitmapFactory.decodeStream(is);
showImageView.setImageBitmap(bitmap);
}catch(Exceptione){
e.printStackTrace();
}
}
//直接使用URLConnection对象进行连接
if(v==urlConnectionBtn){
try{
URLurl=newURL("http://192.168.1.100:8080/myweb/hello.jsp");
URLConnectionconnection=url.openConnection();
InputStreamis=connection.getInputStream();
byte[]bs=newbyte[1024];
intlen=0;
StringBuffersb=newStringBuffer();
while((len=is.read(bs))!=-1){
Stringstr=newString(bs,0,len);
sb.append(str);
}
showTextView.setText(sb.toString());
}catch(Exceptione){
e.printStackTrace();
}
}
//直接使用HttpURLConnection对象进行连接
if(v==httpUrlConnectionBtn){
try{
URLurl=newURL(
"http://192.168.1.100:8080/myweb/hello.jsp?username=abc");
HttpURLConnectionconnection=(HttpURLConnection)url
.openConnection();
connection.setRequestMethod("GET");
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
Stringmessage=connection.getResponseMessage();
showTextView.setText(message);
}
}catch(Exceptione){
e.printStackTrace();
}
}
//使用ApacheHttp客户端进行连接(重要方法)
if(v==httpClientBtn){
try{
HttpClientclient=newDefaultHttpClient();
//如果是Get提交则创建HttpGet对象,否则创建HttpPost对象
//HttpGethttpGet=new
//HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");
//post提交的方式
HttpPosthttpPost=newHttpPost(
"http://192.168.1.100:8080/myweb/hello.jsp");
//如果是Post提交可以将参数封装到集合中传递
ListdataList=newArrayList();
dataList.add(newBasicNameValuePair("username","aaaaa"));
dataList.add(newBasicNameValuePair("pwd","123"));
//UrlEncodedFormEntity用于将集合转换为Entity对象
httpPost.setEntity(newUrlEncodedFormEntity(dataList));
//获取相应消息
HttpResponsehttpResponse=client.execute(httpPost);
//获取消息内容
HttpEntityentity=httpResponse.getEntity();
//把消息对象直接转换为字符串
Stringcontent=EntityUtils.toString(entity);
//showTextView.setText(content);
//通过webview来解析网页
webView.loadDataWithBaseURL(null,content,"text/html","utf-8",null);
//给点url来进行解析
//webView.loadUrl(url);
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
三、使用webService
publicclassLoginActivityextendsActivityimplementsOnClickListener{
privateButtonloginBtn;
privatestaticfinalStringSERVICE_URL="http://192.168.1.100:8080/loginservice/LoginServicePort";
privatestaticfinalStringNAMESPACE="http://service.lovo.com/";
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.login_main);
loginBtn=(Button)findViewById(R.id.login_main_btn_login);
loginBtn.setOnClickListener(this);
}
@Override
publicvoidonClick(Viewv){
if(v==loginBtn){
//创建WebService的连接对象
HttpTransportSEhttpSE=newHttpTransportSE(SERVICE_URL);
//通过SOAP1.1协议对象得到envelop
SoapSerializationEnvelopeenvelop=newSoapSerializationEnvelope(SoapEnvelope.VER11);
//根据命名空间和方法名来创建SOAP对象
SoapObjectsoapObject=newSoapObject(NAMESPACE,"validate");
//向调用方法传递参数
soapObject.addProperty("arg0","abc");
soapObject.addProperty("arg1","123");
//将SoapObject对象设置为SoapSerializationEnvelope对象的传出SOAP消息
envelop.bodyOut=soapObject;
try{
//开始调用远程的方法
httpSE.call(null,envelop);
//得到远程方法返回的SOAP对象
SoapObjectresultObj=(SoapObject)envelop.bodyIn;
//根据名为return的键来获取里面的值,这个值就是方法的返回值
StringreturnStr=resultObj.getProperty("return").toString();
Toast.makeText(this,"返回值:"+returnStr,Toast.LENGTH_LONG).show();
}catch(IOExceptione){
e.printStackTrace();
}catch(XmlPullParserExceptione){
e.printStackTrace();
}
}
}
}
相关文章
- android studio不能输入中文_Android模拟器
- strictmode android,Android 应用性能优化-StrictMode(严格模式)
- 【Android布局】在程序中设置android gravity 和 android layout Gravity属性
- Android studio 一个项目引入另一个项目作为Libary「建议收藏」
- android 触屏事件总结
- Android六大布局
- android计算器开发实例_安卓开发计算器代码
- Android studio更新后出现警告:Warning:The `android.dexOptions.incremental` property is deprecated and it has
- 【Android 安全】DEX 加密 ( 常用 Android 反编译工具 | apktool | dex2jar | enjarify | jd-gui | jadx )
- 反转!马斯克正在求被裁工程师复职,尤其是Android和iOS开发
- 【Android 逆向】类加载器 ClassLoader ( 加载 Android 组件的类加载器 | 双亲委派机制实例分析 )
- 【错误记录】编译 Android 版本的 ijkplayer 报错 ( You must define ANDROID_NDK before starting. | 下载指定版本 NDK )
- [android] 手机卫士黑名单功能(ListView优化)详解手机开发
- 初识Android详解手机开发
- Android编程下字库的使用及注意事项
- 在Android中获取正在运行的Service实例
- Android利用方向传感器获得手机的相对角度实例说明
- Android从服务器获取图片的实例方法
- android之HttpPost&HttpGet使用方法介绍
- Android中自定义对话框(Dialog)的实例代码
- Android进阶篇-自定义图片伸缩控件具体实例
- android获取当前手机号示例程序
- android使用gesturedetector手势识别示例分享
- Android计算器简单逻辑实现实例分享
- Android网络编程之UDP通信模型实例
- Android中使用ViewFlipper进行手势切换实例