谈谈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
猜你喜欢
- 这篇文章主要介绍了Springboot2.0处理自定义异常并返回json,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考
- 使用ApplicationContext获取bean对象编写一个ApplicationContextFactory工厂类public cla
- 背景分析在项目的开发中,不管是对底层的数据逻辑操作过程,还是业务逻辑的处理过程,还是控制逻辑的处理过程,都不可避免会遇到各种可预知的、不可预
- 前言在SpringBoot中,对于JavaBean的属性一般都绑定在配置文件中,比如application.properties/appli
- 1、Swagger是啥Swagger 是一个用于生成、描述和调用 RESTful 接口的 Web 服务。通俗的来讲,Swagger
- springmvc dao层和service层的区别首先解释面上意思,service是业务层,dao是数据访问层这个问题我曾经也有过,记得以
- 线程启动:1.start() 和 run()的区别说明start() : 它的作用是启动一个新线程,新线程会执行相应的run()方法。sta
- Spring EL表达式语言,支持在XML和注解中表达式,类是于JSP的EL表达式语言。在Spring开发中经常涉及调用各种资源的情况,包含
- 我们都知道,当RecyclerView数据源更新后,还需要通过adapter调用对应的方法,从而让RecyclerView重新绘制页面本次也
- 本文实例为大家分享了利用Swing绘制一个动态时钟的具体代码,供大家参考,具体内容如下效果代码在下面,可跳过解析。前言编程实现一个时钟利用S
- 前言:文件的上传和下载在日常开发中很是常见,那么这一功能是如何实现的呢,下面我给大家介绍一下实现条件:1、需要一个form标签,method
- 本文实例为大家分享了Java实现聊天室界面的具体代码,供大家参考,具体内容如下服务器端:package Server; impor
- 一般而言,一个项目部署的由:拉取代码->构建->测试->打包->部署等过程组成,如果我们经常需要部署项目,特别是在微
- 一、什么是热部署?热部署,就是在应用正在运行的时候升级软件,却不需要重新启动应用。二、什么是SpringBoot热部署?SpringBoot
- 以前公司的产品已经上线20多年了,主要是维护,也就是改bug。每周我们Team会从Jira上拿我们可以改的bug,因为每个团队负责的业务范围
- 1. 概述官方JavaDocsApi: javax.swing.JPanelJPanel,面板。JPanel 是在开发中使用频率非常高的一般
- 今天安装了jdk1.8、tomcat8、和maven3.5.2,弄好后在myeclipse新建了一个maven项目,项目默认是jdk1.5,
- 1、什么是Java反射机制?在程序运行中动态地获取类的相关属性,同时调用对象的方法和获取属性,这种机制被称之为Java反射机制下面给出一个反
- 前言在使用Java开发接口请求中,我们需要对请求进行进行统一返回值,这时候我们自己封装一个统一的Result返回类,下面就介绍下我用的这种的
- 项目中要使用到在线支付功能 目前常用的在线支付手段主要是 支付宝 和微信。 这里我使用的是支付宝支付,支付宝有个好处就是他有一个沙箱模式 即