android 網(wǎng)絡(luò)編程之網(wǎng)絡(luò)通信幾種方式實(shí)例分享
如今,手機(jī)應(yīng)用滲透到各行各業(yè),數(shù)量難以計(jì)數(shù),其中大多數(shù)應(yīng)用都會(huì)使用到網(wǎng)絡(luò),與服務(wù)器的交互勢(shì)不可擋,那么android當(dāng)中訪問網(wǎng)絡(luò)有哪些方式呢?
現(xiàn)在總結(jié)了六種方式:
(1)針對(duì)TCP/IP的Socket、ServerSocket
(2)針對(duì)UDP的DatagramSocket、DatagramPackage。這里需要注意的是,考慮到Android設(shè)備通常是手持終端,IP都是隨著上網(wǎng)進(jìn)行分配的。不是固定的。因此開發(fā)也是有一點(diǎn)與普通互聯(lián)網(wǎng)應(yīng)用有所差異的。
(3)針對(duì)直接URL的HttpURLConnection。
(4)Google集成了Apache HTTP客戶端,可使用HTTP進(jìn)行網(wǎng)絡(luò)編程。
(5)使用WebService。Android可以通過開源包如jackson去支持Xmlrpc和Jsonrpc,另外也可以用Ksoap2去實(shí)現(xiàn)Webservice。
(6)直接使用WebView視圖組件顯示網(wǎng)頁?;赪ebView 進(jìn)行開發(fā),Google已經(jīng)提供了一個(gè)基于chrome-lite的Web瀏覽器,直接就可以進(jìn)行上網(wǎng)瀏覽網(wǎng)頁。
一、socket與serverSocket
客戶端代碼
public class TestNetworkActivity extends Activity implements OnClickListener{
private Button connectBtn;
private Button sendBtn;
private TextView showView;
private EditText msgText;
private Socket socket;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_network_main);
connectBtn = (Button) findViewById(R.id.test_network_main_btn_connect);
sendBtn = (Button) findViewById(R.id.test_network_main_btn_send);
showView = (TextView) findViewById(R.id.test_network_main_tv_show);
msgText = (EditText) findViewById(R.id.test_network_main_et_msg);
connectBtn.setOnClickListener(this);
sendBtn.setOnClickListener(this);
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String data = msg.getData().getString("msg");
showView.setText("來自服務(wù)器的消息:"+data);
}
};
}
@Override
public void onClick(View v) {
//連接服務(wù)器
if(v == connectBtn){
connectServer();
}
//發(fā)送消息
if(v == sendBtn){
String msg = msgText.getText().toString();
send(msg);
}
}
/**
*連接服務(wù)器的方法
*/
public void connectServer(){
try {
socket = new Socket("192.168.1.100",4000);
System.out.println("連接服務(wù)器成功");
recevie();
} catch (Exception e) {
System.out.println("連接服務(wù)器失敗"+e);
e.printStackTrace();
}
}
/**
*發(fā)送消息的方法
*/
public void send(String msg){
try {
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println(msg);
ps.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*讀取服務(wù)器傳回的方法
*/
public void recevie(){
new Thread(){
public void run(){
while(true){
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("msg", str);
message.setData(bundle);
handler.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
二、RUL、URLConnection、httpURLConnection、ApacheHttp、WebView
public class TestURLActivity extends Activity implements OnClickListener {
private Button connectBtn;
private Button urlConnectionBtn;
private Button httpUrlConnectionBtn;
private Button httpClientBtn;
private ImageView showImageView;
private TextView showTextView;
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_url_main);
connectBtn = (Button) findViewById(R.id.test_url_main_btn_connect);
urlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_urlconnection);
httpUrlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_httpurlconnection);
httpClientBtn = (Button) findViewById(R.id.test_url_main_btn_httpclient);
showImageView = (ImageView) findViewById(R.id.test_url_main_iv_show);
showTextView = (TextView) findViewById(R.id.test_url_main_tv_show);
webView = (WebView) findViewById(R.id.test_url_main_wv);
connectBtn.setOnClickListener(this);
urlConnectionBtn.setOnClickListener(this);
httpUrlConnectionBtn.setOnClickListener(this);
httpClientBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// 直接使用URL對(duì)象進(jìn)行連接
if (v == connectBtn) {
try {
URL url = new URL("http://192.168.1.100:8080/myweb/image.jpg");
InputStream is = url.openStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
showImageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
// 直接使用URLConnection對(duì)象進(jìn)行連接
if (v == urlConnectionBtn) {
try {
URL url = new URL("http://192.168.1.100:8080/myweb/hello.jsp");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
byte[] bs = new byte[1024];
int len = 0;
StringBuffer sb = new StringBuffer();
while ((len = is.read(bs)) != -1) {
String str = new String(bs, 0, len);
sb.append(str);
}
showTextView.setText(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
// 直接使用HttpURLConnection對(duì)象進(jìn)行連接
if (v == httpUrlConnectionBtn) {
try {
URL url = new URL(
"http://192.168.1.100:8080/myweb/hello.jsp?username=abc");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String message = connection.getResponseMessage();
showTextView.setText(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 使用ApacheHttp客戶端進(jìn)行連接(重要方法)
if (v == httpClientBtn) {
try {
HttpClient client = new DefaultHttpClient();
// 如果是Get提交則創(chuàng)建HttpGet對(duì)象,否則創(chuàng)建HttpPost對(duì)象
// HttpGet httpGet = new
// HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");
// post提交的方式
HttpPost httpPost = new HttpPost(
"http://192.168.1.100:8080/myweb/hello.jsp");
// 如果是Post提交可以將參數(shù)封裝到集合中傳遞
List dataList = new ArrayList();
dataList.add(new BasicNameValuePair("username", "aaaaa"));
dataList.add(new BasicNameValuePair("pwd", "123"));
// UrlEncodedFormEntity用于將集合轉(zhuǎn)換為Entity對(duì)象
httpPost.setEntity(new UrlEncodedFormEntity(dataList));
// 獲取相應(yīng)消息
HttpResponse httpResponse = client.execute(httpPost);
// 獲取消息內(nèi)容
HttpEntity entity = httpResponse.getEntity();
// 把消息對(duì)象直接轉(zhuǎn)換為字符串
String content = EntityUtils.toString(entity);
//showTextView.setText(content);
//通過webview來解析網(wǎng)頁
webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
//給點(diǎn)url來進(jìn)行解析
//webView.loadUrl(url);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
三、使用webService
public class LoginActivity extends Activity implements OnClickListener{
private Button loginBtn;
private static final String SERVICE_URL = "http://192.168.1.100:8080/loginservice/LoginServicePort";
private static final String NAMESPACE = "http://service.lovo.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_main);
loginBtn = (Button) findViewById(R.id.login_main_btn_login);
loginBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v == loginBtn){
//創(chuàng)建WebService的連接對(duì)象
HttpTransportSE httpSE = new HttpTransportSE(SERVICE_URL);
//通過SOAP1.1協(xié)議對(duì)象得到envelop
SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//根據(jù)命名空間和方法名來創(chuàng)建SOAP對(duì)象
SoapObject soapObject = new SoapObject(NAMESPACE, "validate");
//向調(diào)用方法傳遞參數(shù)
soapObject.addProperty("arg0", "abc");
soapObject.addProperty("arg1","123");
//將SoapObject對(duì)象設(shè)置為SoapSerializationEnvelope對(duì)象的傳出SOAP消息
envelop.bodyOut = soapObject;
try {
//開始調(diào)用遠(yuǎn)程的方法
httpSE.call(null, envelop);
//得到遠(yuǎn)程方法返回的SOAP對(duì)象
SoapObject resultObj = (SoapObject) envelop.bodyIn;
//根據(jù)名為return的鍵來獲取里面的值,這個(gè)值就是方法的返回值
String returnStr = resultObj.getProperty("return").toString();
Toast.makeText(this, "返回值:"+returnStr, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
}
相關(guān)文章
Android開發(fā)中的重力傳感器用法實(shí)例詳解
這篇文章主要介紹了Android開發(fā)中的重力傳感器用法,簡單分析了Android重力傳感器的基本功能、使用方法,并結(jié)合實(shí)例形式分析了Android基于重力傳感器實(shí)現(xiàn)橫豎屏切換的相關(guān)操作技巧,需要的朋友可以參考下2017-11-11Android View 完美實(shí)現(xiàn)EditText 在軟鍵盤上邊的示例
本篇文章主要介紹了Android View 完美實(shí)現(xiàn)EditText 在軟鍵盤上邊的示例,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08Android游戲開發(fā)學(xué)習(xí)②焰火綻放效果實(shí)現(xiàn)方法
這篇文章主要介紹了Android游戲開發(fā)學(xué)習(xí)②焰火綻放效果實(shí)現(xiàn)方法,以實(shí)例形式詳細(xì)分析了Android中粒子對(duì)象類Particle類和粒子集合類ParticleSet類及物理引擎ParticleThread類 的使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10Android創(chuàng)建服務(wù)之started service詳細(xì)介紹
這篇文章主要介紹了Android創(chuàng)建服務(wù)之started service,需要的朋友可以參考下2014-02-02Android 如何實(shí)現(xiàn)動(dòng)態(tài)申請(qǐng)權(quán)限
這篇文章主要介紹了Android 如何實(shí)現(xiàn)動(dòng)態(tài)申請(qǐng)權(quán)限。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03Android Service(不和用戶交互應(yīng)用組件)案例分析
Service是在一段不定的時(shí)間運(yùn)行在后臺(tái),不和用戶交互應(yīng)用組件,本文將詳細(xì)介紹,需要了解的朋友可以參考下2012-12-12詳解Android如何實(shí)現(xiàn)好的彈層體驗(yàn)效果
當(dāng)前?App?的設(shè)計(jì)趨勢(shì)越來越希望給用戶沉浸式體驗(yàn),這種設(shè)計(jì)會(huì)讓用戶盡量停留在當(dāng)前的界面,而不需要太多的跳轉(zhuǎn),這就需要引入彈層。本篇我們就來講講彈層這塊需要注意哪些用戶體驗(yàn)2022-11-11