弱龄寄事外,委怀在琴书。这篇文章主要讲述Android 网络相关的知识,希望能为你提供帮助。
基于android开发的应用大多数都会涉及到网络的访问。
在Android中几种网络编程的方式:
(1)针对TCP/IP的Socket、ServerSocket
(2)针对UDP的DatagramSocket、DatagramPackage。这里需要注意的是,考虑到Android设备通常是手持终端,IP都是随着上网进行分配的。不是固定的。因此开发也是有一点与普通互联网应用有所差异的。
(3)针对直接URL的HttpURLConnection
(4)Google集成了Apache HTTP客户端,可使用HTTP进行网络编程。针对HTTP,Google集成了Appache Http core和httpclient 4版本,因此特别注意Android不支持httpclient 3.x系列,而且目前并不支持Multipart(MIME),需要自行添加httpmime.jar
(5)使用Web Service。Android可以通过开源包如jackson去支持Xmlrpc和Jsonrpc,另外也可以用Ksoap2去实现Webservice
(6) 直接使用WebView视图组件显示网页。基于WebView 进行开发,Google已经提供了一个基于chrome-lite的Web浏览器,直接就可以进行上网浏览网页。
下面主要通过实例说明常用的HttpURLConnection,Socket以及开源网络框架OKHttp的使用。
1、HttpUrlConnection
Android中,发送Http请求一般有HttpURLConnection和HttpClient两种,不过由于HttpClient存在API数量过多,扩展困难等缺点,在Android6.0系统中,已被完全弃用。
Http请求方法有GET和POST。GET表示希望从服务器获取数据,而POST表示希望提交数据给服务器。
采用Http的GET方法访问百度站点,返回数据:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button mButton; private TextView mText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = (Button) findViewById(R.id.button); mText = (TextView) findViewById(R.id.text); mButton.setOnClickListener(this); }@Override public void onClick(View v) { switch (v.getId()){ case R.id.button: sendRequestByHttpURLConnection(); } }public void sendRequestByHttpURLConnection(){ new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; BufferedReader reader = null; try{ URL url = new URL("https://www.baidu.com"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); InputStream in = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(in)); final StringBuffer respones = new StringBuffer(); String line; while ((line = reader.readLine()) != null){ respones.append(line); } runOnUiThread(new Runnable() { @Override public void run() { mText.setText(respones.toString()); } }); }catch (Exception e){ e.printStackTrace(); }finally { if (reader != null){ try{ reader.close(); }catch (IOException e){ e.printStackTrace(); } } if (connection != null){ connection.disconnect(); } } } }).start(); } }
2、开源OkHttp https://github.com/square/okhttp
添加OkHttp库的依赖
compile ‘com.squareup.okhttp3:okhttp:3.6.0
import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button mButton; private TextView mText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = (Button) findViewById(R.id.button); mText = (TextView) findViewById(R.id.text); mButton.setOnClickListener(this); }@Override public void onClick(View v) { switch (v.getId()){ case R.id.button: sendRequestByOkHttp(); } }public void sendRequestByOkHttp(){ new Thread(new Runnable() { @Override public void run() { try{ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("https://www.baidu.com").build(); Response response = client.newCall(request).execute(); final String text = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { mText.setText(text); } }); }catch (Exception e){ e.printStackTrace(); } } }).start(); } }
更具体的用法参照:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html
3、Socket网络
TCP/IP是一种协议,是一种面向连接的、可靠的协议,通过三次握手连接和四次挥手断开连接。Socket仅仅是对TCP、UDP网络接口的封装,不涉及上层协议。TCP、UDP传输特性不同,分别适用于不同类型的应用层协议,其中TCP有连接,延时较长,能保证服务质量;UDP无连接,需要应用程序进行数据分包、延时短,效率高,数据包可能丢失或到达对端发生顺序混乱。
下面实现服务端接收客户端发送的消息。
服务端:
public class Service extends IntentService{ /** * Creates an IntentService.Invoked by your subclass‘s constructor. * * @param name Used to name the worker thread, important only for debugging. */ public Service(String name) { super(name); } public Service (){ super("Service"); }@Nullable @Override public IBinder onBind(Intent intent) { return null; }@Override protected void onHandleIntent(Intent intent) { Socket socket = null; try { ServerSocket server= new ServerSocket(9999); while (true){ socket = server.accept(); if (socket.isConnected()){ Log.d("azheng", "service:succesful"); } BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String message = reader.readLine(); Log.d("azheng", "service: text form client is :" + message); // PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true); out.println(message); } }catch (UnknownHostException e){ e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }@Override public void onCreate() { super.onCreate(); }@Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); }@Override public void onDestroy() { super.onDestroy(); } }
客户端:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button mButton; private EditText mText; private Button mConnect; private String ip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = (Button) findViewById(R.id.button); mText = (EditText) findViewById(R.id.text); mConnect = (Button)findViewById(R.id.connect); ip = getLocalIpAddress(); mButton.setOnClickListener(this); mConnect.setOnClickListener(this); }@Override public void onClick(View v) { Socket client = null; switch (v.getId()){ case R.id.connect: Intent intent = new Intent(MainActivity.this,Service.class); startService(intent); break; case R.id.button: new Thread(new Runnable() { @Override public void run() { Socket client = null; try{ //send String message = mText.getText().toString(); client = new Socket(ip,9999); if (client.isConnected()){ Log.d("azheng", "client:successful"); } PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true); out.println(message); }catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); break; } }public String getLocalIpAddress() {try {for (Enumeration< NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements(); ) {NetworkInterface intf = en.nextElement(); for (Enumeration< InetAddress> enumIpAddr = intf .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) {return inetAddress.getHostAddress().toString(); }}}} catch (SocketException ex) { ex.printStackTrace(); } return null; } }
参考:
http://blog.csdn.net/yuzhiboyi/article/details/7733054
【Android 网络】 http://blog.csdn.net/yuzhiboyi/article/details/7743390
推荐阅读
- HDU6020---MG loves apple(枚举)
- Android底部导航BottomNavigationBar
- XamarinAndroid 自动绑定View变量
- android gralloc是什么意思
- 填坑实录Android Studio 利用 ADB WIFI 插件实现真机无线调试
- Android弹幕实现(基于B站弹幕开源系统-重构)
- Android性能优化系列之Bitmap图片优化
- LeetCode 448. Find All Numbers Disappeared in an Array
- Android studio 相关下载