談?wù)凙ndroid的三種網(wǎng)絡(luò)通信方式
Android平臺(tái)有三種網(wǎng)絡(luò)接口可以使用,他們分別是:java.net.*(標(biāo)準(zhǔn)Java接口)、Org.apache接口和Android.net.*(Android網(wǎng)絡(luò)接口)。下面分別介紹這些接口的功能和作用。
1.標(biāo)準(zhǔn)Java接口
java.net.*提供與聯(lián)網(wǎng)有關(guān)的類,包括流、數(shù)據(jù)包套接字(socket)、Internet協(xié)議、常見(jiàn)Http處理等。比如:創(chuàng)建URL,以及URLConnection/HttpURLConnection對(duì)象、設(shè)置鏈接參數(shù)、鏈接到服務(wù)器、向服務(wù)器寫數(shù)據(jù)、從服務(wù)器讀取數(shù)據(jù)等通信。這些在Java網(wǎng)絡(luò)編程中均有涉及,我們看一個(gè)簡(jiǎn)單的socket編程,實(shí)現(xiàn)服務(wù)器回發(fā)客戶端信息。
服務(wù)端:
public class Server implements Runnable{
@Override
public void run() {
Socket socket = null;
try {
ServerSocket server = new ServerSocket(18888);
//循環(huán)監(jiān)聽(tīng)客戶端鏈接請(qǐng)求
while(true){
System.out.println("start...");
//接收請(qǐng)求
socket = server.accept();
System.out.println("accept...");
//接收客戶端消息
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = in.readLine();
//發(fā)送消息,向客戶端
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println("Server:" + message);
//關(guān)閉流
in.close();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if (null != socket){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//啟動(dòng)服務(wù)器
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 {
//創(chuàng)建客戶端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);
//發(fā)送數(shù)據(jù)
out.println(message);
//接收數(shù)據(jù)
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>
啟動(dòng)服務(wù)器:
javac com/test/socket/Server.java java com.test.socket.Server
運(yùn)行客戶端程序:
結(jié)果如圖:


注意:服務(wù)器與客戶端無(wú)法鏈接的可能原因有:
沒(méi)有加訪問(wèn)網(wǎng)絡(luò)的權(quán)限:<uses-permission android:name="android.permission.INTERNET"></uses-permission>
IP地址要使用:10.0.2.2
模擬器不能配置代理。
2。Apache接口
對(duì)于大部分應(yīng)用程序而言JDK本身提供的網(wǎng)絡(luò)功能已遠(yuǎn)遠(yuǎn)不夠,這時(shí)就需要Android提供的Apache HttpClient了。它是一個(gè)開(kāi)源項(xiàng)目,功能更加完善,為客戶端的Http編程提供高效、最新、功能豐富的工具包支持。
下面我們以一個(gè)簡(jiǎn)單例子來(lái)看看如何使用HttpClient在Android客戶端訪問(wèn)Web。
首先,要在你的機(jī)器上搭建一個(gè)web應(yīng)用myapp,只有很簡(jiǎn)單的一個(gè)http.jsp
內(nèi)容如下:
<%@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>
然后實(shí)現(xiàn)Android客戶端,分別以post、get方式去訪問(wèn)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">通過(guò)按鈕選擇不同方式訪問(wèn)網(wǎng)頁(yè)</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);
//綁定按鈕監(jiān)聽(tīng)器
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方式發(fā)送請(qǐng)求";
textView.setText(get(uri));
}
});
//綁定按鈕監(jiān)聽(tīng)器
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方式發(fā)送請(qǐng)求,訪問(wèn)web
* @param uri web地址
* @return 響應(yīng)數(shù)據(jù)
*/
private static String get(String uri){
BufferedReader reader = null;
StringBuffer sb = null;
String result = "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(uri);
try {
//發(fā)送請(qǐng)求,得到響應(yīng)
HttpResponse response = client.execute(request);
//請(qǐng)求成功
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方式發(fā)送請(qǐng)求,訪問(wèn)web
* @param uri web地址
* @return 響應(yīng)數(shù)據(jù)
*/
private static String post(String uri){
BufferedReader reader = null;
StringBuffer sb = null;
String result = "";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(uri);
//保存要傳遞的參數(shù)
List<NameValuePair> params = new ArrayList<NameValuePair>();
//添加參數(shù)
params.add(new BasicNameValuePair("parameter","以Post方式發(fā)送請(qǐng)求"));
try {
//設(shè)置字符集
HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8");
//請(qǐng)求對(duì)象
request.setEntity(entity);
//發(fā)送請(qǐng)求
HttpResponse response = client.execute(request);
//請(qǐng)求成功
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 {
//關(guān)閉流
if (null != reader){
reader.close();
reader = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != sb){
result = sb.toString();
}
return result;
}
}
運(yùn)行結(jié)果如下:


3.android.net編程:
常常使用此包下的類進(jìn)行Android特有的網(wǎng)絡(luò)編程,如:訪問(wèn)WiFi,訪問(wèn)Android聯(lián)網(wǎng)信息,郵件等功能。這里不詳細(xì)講。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android實(shí)現(xiàn)志愿者系統(tǒng)詳細(xì)步驟與代碼
這篇文章主要介紹了Android實(shí)現(xiàn)志愿者系統(tǒng),本系統(tǒng)采用MVC架構(gòu)設(shè)計(jì),SQLite數(shù)據(jù)表有用戶表、成員表和活動(dòng)表,有十多個(gè)Activity頁(yè)面。打開(kāi)應(yīng)用,進(jìn)入歡迎界面,3s后跳轉(zhuǎn)登錄界面,用戶先注冊(cè)賬號(hào),登錄成功后進(jìn)入主界面2023-02-02
android-wheel控件實(shí)現(xiàn)三級(jí)聯(lián)動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了android-wheel控件實(shí)現(xiàn)三級(jí)聯(lián)動(dòng)效果的代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10
Android通過(guò)JNI實(shí)現(xiàn)守護(hù)進(jìn)程
這篇文章主要為大家詳細(xì)介紹了Android通過(guò)JNI實(shí)現(xiàn)守護(hù)進(jìn)程的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-09-09
利用Android中的TextView實(shí)現(xiàn)逐字顯示動(dòng)畫
在安卓程序啟動(dòng)的時(shí)候,想逐字顯示一段話,每個(gè)字都有一個(gè)從透明到不透明的漸變動(dòng)畫。那如何顯示這個(gè)效果,下面一起來(lái)看看。2016-08-08
Android開(kāi)發(fā)TextvView實(shí)現(xiàn)鏤空字體效果示例代碼
這篇文章主要介紹了Android開(kāi)發(fā)TextvView實(shí)現(xiàn)鏤空字體效果,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
Android registerForActivityResult動(dòng)態(tài)申請(qǐng)權(quán)限案例詳解
這篇文章主要介紹了Android registerForActivityResult動(dòng)態(tài)申請(qǐng)權(quán)限案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09
Android實(shí)現(xiàn)使用微信登錄第三方APP的方法
這篇文章主要介紹了Android實(shí)現(xiàn)使用微信登錄第三方APP的方法,結(jié)合實(shí)例形式分析了Android微信登錄APP的操作步驟與具體功能實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-11-11
Bootstrap 下拉菜單.dropdown的具體使用方法
這篇文章主要介紹了Bootstrap 下拉菜單.dropdown的具體使用方法,詳細(xì)講解下拉菜單的交互,有興趣的可以了解一下2017-10-10
Android 打開(kāi)相冊(cè)選擇單張圖片實(shí)現(xiàn)代碼
這篇文章主要介紹了Android 打開(kāi)相冊(cè)選擇單張圖片實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-05-05

