谈谈Android的三种网络通信方式
作者:YAnG_Linux 发布时间:2023-04-19 17:28:47
Android平台有三种网络接口可以使用,他们分别是:java.net.*(标准Java接口)、Org.apache接口和Android.net.*(Android网络接口)。下面分别介绍这些接口的功能和作用。
1.标准Java接口
java.net.*提供与联网有关的类,包括流、数据包套接字(socket)、Internet协议、常见Http处理等。比如:创建URL,以及URLConnection/HttpURLConnection对象、设置链接参数、链接到服务器、向服务器写数据、从服务器读取数据等通信。这些在Java网络编程中均有涉及,我们看一个简单的socket编程,实现服务器回发客户端信息。
服务端:
public class Server implements Runnable{
@Override
public void run() {
Socket socket = null;
try {
ServerSocket server = new ServerSocket(18888);
//循环监听客户端链接请求
while(true){
System.out.println("start...");
//接收请求
socket = server.accept();
System.out.println("accept...");
//接收客户端消息
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = in.readLine();
//发送消息,向客户端
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println("Server:" + message);
//关闭流
in.close();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if (null != socket){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//启动服务器
public static void main(String[] args){
Thread server = new Thread(new Server());
server.start();
}
}
客户端,MainActivity
public class MainActivity extends Activity {
private EditText editText;
private Button button;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText)findViewById(R.id.editText1);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Socket socket = null;
String message = editText.getText().toString()+ "\r\n" ;
try {
//创建客户端socket,注意:不能用localhost或127.0.0.1,Android模拟器把自己作为localhost
socket = new Socket("<span style="font-weight: bold;">10.0.2.2</span>",18888);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter
(socket.getOutputStream())),true);
//发送数据
out.println(message);
//接收数据
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = in.readLine();
if (null != msg){
editText.setText(msg);
System.out.println(msg);
}
else{
editText.setText("data error");
}
out.close();
in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
if (null != socket){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<EditText android:layout_width="match_parent" android:id="@+id/editText1"
android:layout_height="wrap_content"
android:hint="input the message and click the send button"
></EditText>
<Button android:text="send" android:id="@+id/button1"
android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
启动服务器:
javac com/test/socket/Server.java
java com.test.socket.Server
运行客户端程序:
结果如图:
注意:服务器与客户端无法链接的可能原因有:
没有加访问网络的权限:<uses-permission android:name="android.permission.INTERNET"></uses-permission>
IP地址要使用:10.0.2.2
模拟器不能配置代理。
2。Apache接口
对于大部分应用程序而言JDK本身提供的网络功能已远远不够,这时就需要Android提供的Apache HttpClient了。它是一个开源项目,功能更加完善,为客户端的Http编程提供高效、最新、功能丰富的工具包支持。
下面我们以一个简单例子来看看如何使用HttpClient在Android客户端访问Web。
首先,要在你的机器上搭建一个web应用myapp,只有很简单的一个http.jsp
内容如下:
<%@page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title>
Http Test
</title>
</head>
<body>
<%
String type = request.getParameter("parameter");
String result = new String(type.getBytes("iso-8859-1"),"utf-8");
out.println("<h1>" + result + "</h1>");
%>
</body>
</html>
然后实现Android客户端,分别以post、get方式去访问myapp,代码如下:
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:gravity="center"
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button android:text="get" android:id="@+id/get" android:layout_width="match_parent" android:layout_height="wrap_content"></Button>
<Button android:text="post" android:id="@+id/post" android:layout_width="match_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
资源文件:
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">通过按钮选择不同方式访问网页</string>
<string name="app_name">Http Get</string>
</resources>
主Activity:
public class MainActivity extends Activity {
private TextView textView;
private Button get,post;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView);
get = (Button)findViewById(R.id.get);
post = (Button)findViewById(R.id.post);
//绑定按钮 *
get.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//注意:此处ip不能用127.0.0.1或localhost,Android模拟器已将它自己作为了localhost
String uri = "http://192.168.22.28:8080/myapp/http.jsp?parameter=以Get方式发送请求";
textView.setText(get(uri));
}
});
//绑定按钮 *
post.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String uri = "http://192.168.22.28:8080/myapp/http.jsp";
textView.setText(post(uri));
}
});
}
/**
* 以get方式发送请求,访问web
* @param uri web地址
* @return 响应数据
*/
private static String get(String uri){
BufferedReader reader = null;
StringBuffer sb = null;
String result = "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(uri);
try {
//发送请求,得到响应
HttpResponse response = client.execute(request);
//请求成功
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
sb = new StringBuffer();
String line = "";
String NL = System.getProperty("line.separator");
while((line = reader.readLine()) != null){
sb.append(line);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
if (null != reader){
reader.close();
reader = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != sb){
result = sb.toString();
}
return result;
}
/**
* 以post方式发送请求,访问web
* @param uri web地址
* @return 响应数据
*/
private static String post(String uri){
BufferedReader reader = null;
StringBuffer sb = null;
String result = "";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(uri);
//保存要传递的参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
//添加参数
params.add(new BasicNameValuePair("parameter","以Post方式发送请求"));
try {
//设置字符集
HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8");
//请求对象
request.setEntity(entity);
//发送请求
HttpResponse response = client.execute(request);
//请求成功
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
System.out.println("post success");
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
sb = new StringBuffer();
String line = "";
String NL = System.getProperty("line.separator");
while((line = reader.readLine()) != null){
sb.append(line);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
//关闭流
if (null != reader){
reader.close();
reader = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != sb){
result = sb.toString();
}
return result;
}
}
运行结果如下:
3.android.net编程:
常常使用此包下的类进行Android特有的网络编程,如:访问WiFi,访问Android联网信息,邮件等功能。这里不详细讲。
来源:http://blog.csdn.net/yuzhiboyi/article/details/7743390


猜你喜欢
- Java反射动态修改注解的某个属性值昨晚看到一条问题,大意是楼主希望可以动态得建立多个Spring 的定时任务。这个题目我并不是很熟悉,不过
- 很多Android手机上都配有LED灯,比如HTC的手机在充电、新来短信等时候都会有响应的指示,其实很简单的这都是NotificationM
- JenkinsJenkins是一个开源的、可扩展的持续集成、交付、部署的基于web界面的平台。允许持续集成和持续交付项目,无论用的是什么平台
- 本文实例讲述了Android编程实现全局获取Context及使用Intent传递对象的方法。分享给大家供大家参考,具体如下:一、全局获取 C
- 本文介绍了SpringBoot结合SpringSecurity实现图形验证码功能,分享给大家,具体如下:生成图形验证码根据随机数生成图片将随
- 静态方法可以不用创建对象就调用,非静态方法必须有了对象的实例才能调用。因此想在静态方法中直接引用非静态方法是不可能的,因为不知道调用哪个对象
- 什么是Java垃圾回收器Java垃圾回收器是Java虚拟机(JVM)的三个重要模块(另外两个是解释器和多线程机制)之一,为应用程序提供内存的
- 本章是后续学习的基石,只有充分理解了分布式系统的概念和面临的问题,以及ZooKeeper内部的概念,才能懂得ZooKeeper是如何对分布式
- 本文实例讲述了java实现统计字符串中字符及子字符串个数的方法。分享给大家供大家参考,具体如下:这里用java实现统计字符串中的字符(包括数
- 前言Go 语言比 Java 语言性能优越的一个原因,就是轻量级线程Goroutines(协程Coroutine)。本篇文章深入分析下 Jav
- 前言最近做项目的时候遇到一个卡劵的效果,由于自己觉得用图片来做的话可以会出现适配效果不好,再加上自己自定义view方面的知识比较薄弱,所以想
- 平时我们编写WinForm程序经常使用VS进行拖控件的方式,这样做虽然简单,但是无法深入了解WinForm程序的本质。其实,用记事本也可以编
- 前言在H5火热的时代,许多框架都出了底部弹窗的控件,在H5被称为弹出菜单ActionSheet,今天我们也来模仿一个ios的底部弹窗,取材于
- 其中包含两个jsp文件,分别为login.jsp和index.jsp代码如下:login.jsp<%@ page language=&
- Spring是一个非常流行的Java Web开发框架,它提供了强大的依赖注入、面向切面编程、声明式事务管理等功能,为开发者提供了高效、快速地
- 一、需求对于Java开发工程师来说,可能手头上同时负责不同的项目,但是由于历史的原因,Java版本可能没有做到统一升级,有的项目是使用JDK
- 对openfeign不清楚的同学可以参考下我的这篇文章:springboot~openfeign从此和httpClient说再见对于open
- 1、Jetbrains官网下载IntelliJ IDEA1.1 官方网站http://www.jetbrains.com/idea/&nbs
- 为什么需要组件化小项目是不需要组件化的。当一个项目有数十个人开发,编译项目要花费10分钟,修改一个bug就可能会影响到其他业务,小小的改动就
- 在android studio中存储数据有三个方法,分别是:(1)简单存储——SharedPreferences(2)文件存储:内部存储——