如今,手機應用滲透到各行各業,數量難以計數,其中大多數應用都會使用到網絡,與服務器的交互勢不可擋,那么android當中訪問網絡有哪些方式呢?
現在總結了六種方式:
(1)針對TCP/IP的Socket、ServerSocket
(2)針對UDP的DatagramSocket、DatagramPackage。這里需要注意的是,考慮到Android設備通常是手持終端,IP都是隨著上網進行分配的。不是固定的。因此開發也是有一點與普通互聯網應用有所差異的。
(3)針對直接URL的HttpURLConnection。
(4)Google集成了Apache HTTP客戶端,可使用HTTP進行網絡編程。
(5)使用WebService。Android可以通過開源包如jackson去支持Xmlrpc和Jsonrpc,另外也可以用Ksoap2去實現Webservice。
(6)直接使用WebView視圖組件顯示網頁?;赪ebView 進行開發,Google已經提供了一個基于chrome-lite的Web瀏覽器,直接就可以進行上網瀏覽網頁。
一、socket與serverSocket
客戶端代碼
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("來自服務器的消息:"+data);
}
};
}
@Override
public void onClick(View v) {
//連接服務器
if(v == connectBtn){
connectServer();
}
//發送消息
if(v == sendBtn){
String msg = msgText.getText().toString();
send(msg);
}
}
/**
*連接服務器的方法
*/
public void connectServer(){
try {
socket = new Socket("192.168.1.100",4000);
System.out.println("連接服務器成功");
recevie();
} catch (Exception e) {
System.out.println("連接服務器失敗"+e);
e.printStackTrace();
}
}
/**
*發送消息的方法
*/
public void send(String msg){
try {
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println(msg);
ps.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*讀取服務器傳回的方法
*/
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
@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對象進行連接
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對象進行連接
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對象進行連接
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客戶端進行連接(重要方法)
if (v == httpClientBtn) {
try {
HttpClient client = new DefaultHttpClient();
// 如果是Get提交則創建HttpGet對象,否則創建HttpPost對象
// 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提交可以將參數封裝到集合中傳遞
List dataList = new ArrayList();
dataList.add(new BasicNameValuePair("username", "aaaaa"));
dataList.add(new BasicNameValuePair("pwd", "123"));
// UrlEncodedFormEntity用于將集合轉換為Entity對象
httpPost.setEntity(new UrlEncodedFormEntity(dataList));
// 獲取相應消息
HttpResponse httpResponse = client.execute(httpPost);
// 獲取消息內容
HttpEntity entity = httpResponse.getEntity();
// 把消息對象直接轉換為字符串
String content = EntityUtils.toString(entity);
//showTextView.setText(content);
//通過webview來解析網頁
webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
//給點url來進行解析
//webView.loadUrl(url);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
三、使用webService
新聞熱點
疑難解答
圖片精選