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 >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联网信息,邮件等功能。这里不详细讲。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的谈谈Android的三种网络通信方式全部内容,希望文章能够帮你解决谈谈Android的三种网络通信方式所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)