Android三种⽹络通讯⽅式及Android的⽹络通讯机制Android平台有三种⽹络接⼝可以使⽤,他们分别是:java.*(标准Java接⼝)、Org.apache接⼝和Android.*(Android⽹络接⼝)。下⾯分别介绍这些接⼝的功能和作⽤。
1.标准Java接⼝
java.*提供与联⽹有关的类,包括流、数据包套接字(socket)、Internet协议、常见Http处理等。⽐如:创建URL,以及URLConnection/HttpURLConnection对象、设置链接参数、链接到服务器、向服务器写数据、从服务器读取数据等通信。这些在Java⽹络编程中均有涉及,我们看⼀个简单的socket编程,实现服务器回发客户端信息。
下⾯⽤个例⼦来说明:
A、客户端:
新建Android项⽬⼯程:SocketForAndroid(这个随意起名字了吧,我是以这个建⽴的!)
下⾯是l的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="schemas.android/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<EditText
android:id="@+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint" />
<Button
android:id="@+id/send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/send" />
</LinearLayout>
MainActivity.java的代码⼊下:
package com.yaowen.socketforandroid;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.Socket;
public class MainActivity extends AppCompatActivity {
private EditText message;
private Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
//初始化两个UI控件
message = (EditText) findViewById(ssage);
send = (Button) findViewById(R.id.send);
//设置发送按钮的点击事件响应
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Socket socket = null;
//获取message输⼊框⾥的输⼊的内容
String msg = Text().toString() + "\r\n";
try {
//这⾥必须是192.168.3.200,不可以是localhost或者127.0.0.1
socket = new Socket("192.168.3.200", 18888);
PrintWriter out = new PrintWriter(
new BufferedWriter(
android模拟点击
new OutputStreamWriter(
)
), true);
//发送消息
out.println(msg);
//接收数据
BufferedReader in = new BufferedReader(
new InputStreamReader(
)
)
;
//读取接收的数据
String msg_in = in.readLine();
if (null != msg_in) {
message.setText(msg_in);
System.out.println(msg_in);
} else {
message.setText("接收的数据有误!");
}
//关闭各种流
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != socket) {
//socket不为空时,最后记得要把socket关闭
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
最后别忘记添加访问⽹络权限:
<uses-permission android:name="android.permission.INTERNET" />
B、服务端:
package service;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.ServerSocket;
import java.Socket;
public class ServerAndroid implements Runnable {
@Override
public void run() {
Socket socket = null;
try {
ServerSocket server = new ServerSocket(18888);
// 循环监听客户端链接请求
while (true) {
System.out.println("");
// 接收请求
socket = server.accept();
System.out.println("");
// 接收客户端消息
BufferedReader in = new BufferedReader(new InputStream())); String message = in.readLine();
System.out.println(message);
// 发送消息,向客户端
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStream())),  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 ServerAndroid());
server.start();
}
}
C、启动服务器,控制台会打印出“”字符串!
D、运⾏Android项⽬⽂件,如下图:
在输⼊框⾥输⼊如下字符串,点发送按钮:
服务器收到客户端发来的消息并打印到控制台:
2、Apache接⼝
对于⼤部分应⽤程序⽽⾔JDK本⾝提供的⽹络功能已远远不够,这时就需要Android提供的Apache HttpClient了。它是⼀个开源项⽬,功能更加完善,为客户端的Http编程提供⾼效、最新、功能丰富的⼯具包⽀持。
下⾯我们以⼀个简单例⼦来看看如何使⽤HttpClient在Android客户端访问Web。
⾸先,要在你的机器上搭建⼀个web应⽤test,有两个很简单的PHP⽂件:hello_get.php和hello_post.php!
内容如下:
hello_get.php的代码如下:
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
You connected this page on : <?php echo $_GET["get"]; ?>
</body>
</html>
hello_post.php的代码如下:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
You connected this page on : <?php echo $_POST["post"]; ?>
</body>
</html>
在原来的Android项⽬⾥新建⼀个Apache活动类:Apache.java,代码如下:
package com.yaowen.socketforandroid;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.ity.UrlEncodedFormEntity;
import org.apache.hods.HttpGet;
import org.apache.hods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.ssage.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by YAOWEN on 2015/11/10.
*/
public class ApacheActivity extends AppCompatActivity implements View.OnClickListener { private TextView textView;
private Button get1, post1;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.apache);
textView = (TextView) findViewById(View);
get1 = (Button) findViewById();
post1 = (Button) findViewById(R.id.post);
get1.setOnClickListener(this);
post1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == ) {
//注意:此处ip不能⽤127.0.0.1或localhost,Android模拟器已将它⾃⼰作为了localhost
String url = "192.168.3.200/test/hello_get.php?name=yaowen&get=GET";
textView.setText(get(url));
}
if (v.getId() == R.id.post) {
String url="192.168.3.200/test/hello_post.php";
textView.setText(post(url));
}
}
/**
* 以post⽅式发送请求,访问web
*
* @param url web地址
* @return 响应数据
*/
private String post(String url) {
BufferedReader reader = null;
StringBuffer sb = null;
String result = "";
HttpClient client = new DefaultHttpClient();
HttpPost requset = new HttpPost(url);
/
/保存要传递的参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
//添加参数
params.add(new BasicNameValuePair("name", "yaowen"));
params.add(new BasicNameValuePair("post","POST"));
try {
HttpEntity entity = new UrlEncodedFormEntity(params, "utf-8");
requset.setEntity(entity);
HttpResponse response = ute(requset);
if (StatusLine().getStatusCode() == 200) {
System.out.println("post success");
reader = new BufferedReader(new Entity().getContent()));    sb = new StringBuffer();
String line = "";
String NL = Property("line.separator");

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。