码迷,mamicode.com
首页 > 移动开发 > 详细

android网络通信方式总结

时间:2014-12-01 17:46:43      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:网络   通信   android   

19951G问世,手机只能进行基本的语音通讯,1996-19972GGSM,CDMA)及其后的GPRSEDGE等技术的快速发展,手机开始逐渐增加了数据服务功能。2009年开始,3G在全世界开始大规模布置以及苹果创造性开发新型苹果手机。手机慢慢的变成互联网的终端,从而带动了一个新的时代--移动互联网时代。因此现代手机通常都支持这些常用网络设备,如WIFI,NFC,蓝牙等。

Android中几种网络编程的方式:

1、针对TCP/IPSocketServerSocket

TCP/IP是一种协议,是一种面向连接的、可靠的协议。Socket仅仅是对TCPUDP网络接口的封装,不涉及上层协议

示例代码:

(1)android客户端

<span style="color:#444444;">import java.io.*;
</span><span style="color:#ff0000;">import java.net.Socket;</span><span style="color:#444444;">
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//客户端的实现
public class TestSocket extends Activity {
	private TextView text1;
	private Button but1;
	private EditText edit1;
	private final String DEBUG_TAG="mySocketAct";


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        text1=(TextView)findViewById(R.id.text1);
        but1=(Button)findViewById(R.id.but1);
        edit1=(EditText)findViewById(R.id.edit);
        
        but1.setOnClickListener(new Button.OnClickListener()
        {
        	@Override
			public void onClick(View v) {
				Socket socket=null;
				String mesg=edit1.getText().toString()+"\r\n";
				edit1.setText("");
				Log.e("dddd", "sent id");
				
				try { 
					socket=new Socket("172.22.122.1",54321);
					//向服务器发送信息
					PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
					out.println(mesg);
					
					//接受服务器的信息
					BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
					String mstr=br.readLine();
					if(mstr!=null)
					{
						text1.setText(mstr);
					}else
					{
						text1.setText("数据错误");
					}
					</span><span style="color:#ff0000;">out.close();
					br.close();
					socket.close();</span><span style="color:#444444;">
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}catch(Exception e)
				{
					Log.e(DEBUG_TAG,e.toString());
				}
			}        	
        });
    }
}</span>
(2)服务端代码

<span style="color:#444444;">import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;


public class AndroidServer implements Runnable{
	public void run() {
		try {
			ServerSocket serverSocket=new ServerSocket(54321);
			while(true)
			{
				System.out.println("等待接收用户连接:");
				//接受客户端请求
				Socket client=serverSocket.accept();
				try
				{
					//接受客户端信息
					BufferedReader in=new</span><span style="color:#ff0000;"> BufferedReader</span><span style="color:#444444;">(new InputStreamReader(client.</span><span style="color:#ff0000;">getInputStream</span><span style="color:#444444;">()));
					String str=in.readLine();
					System.out.println("read:  "+str);
					//向客户端发送消息
					</span><span style="color:#ff0000;">PrintWriter</span><span style="color:#444444;"> out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.</span><span style="color:#ff0000;">getOutputStream</span><span style="color:#444444;">())),true);
					out.println("return	"+str);
					in.close();
					out.close();
				}catch(Exception ex)
				{
					System.out.println(ex.getMessage());
					ex.printStackTrace();
				}
				finally
				{
					</span><span style="color:#ff0000;">client.close();</span><span style="color:#444444;">
					System.out.println("close");
				}
			}
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	public static void main(String [] args)
	{
		Thread desktopServerThread=new Thread(new AndroidServer());
		desktopServerThread.start();
	}
}</span>

2、
针对UDPDatagramSocketDatagramPackage

对于UDP服务端,首先启动侦听服务,然后得到数据包进行处理,组后根据获得数据包进行反馈。UDP socket没有连接的概念,因此构造完成的DatagramSocket不会发出向对端的网络连接请求,在每一个发送的UDP数据包中包含目的地址和端口。因为UDP数据不会在对端进行重新组包,因此一次发送的数据长度必须加以限制。Socket.send(outputPacket);用于发送一个数据包;socket.receive(inputPacket);用于接收一个数据包。

示例代码:

(1)客户端代码

<pre name="code" class="java">public class TestClient {
	static DatagramSocket socket;

	public TestClient() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 * @param ip
	 *            ip地址
	 * @param port
	 *            端口
	 * @param str
	 *            发送的内容
	 */
	public static String clientUDP(String ip, int port, String str) {
		String result = null;
		while (true) {
			try {

				byte[] outputData = str.getBytes();
				// UDP socket 数据发送
				socket = new DatagramSocket();
				DatagramPacket outputPacket = new DatagramPacket(outputData,
						outputData.length, InetAddress.getByName(ip), port);
				socket.send(outputPacket);

				// udp 数据读取
				DatagramPacket inputPacket = new DatagramPacket(new byte[512],
						512);
				socket.receive(inputPacket);
				System.out.println(new String(inputPacket.getData(), 0,
						inputPacket.getLength()));
				result = new String(inputPacket.getData(), 0,
						inputPacket.getLength());

			} catch (Exception e) {
				e.printStackTrace();
			}
			if (socket != null) {
				socket.close();
			}

			return result;
		}
	}
}



(2)服务端代码

package server;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.text.SimpleDateFormat;
import java.util.Date;




public class UDPServer{
    public static void main(String[] args) throws Exception{
            DatagramSocket udpSocket = new DatagramSocket(8080);
            while(true){
                    try{
                            // UDP数据读取
                            DatagramPacket packet = new DatagramPacket(new byte[512],512);
                            udpSocket.receive(packet);
                            String msg = new String(packet.getData(), 0,packet.getLength());
                            System.out.println(msg);
                            if(msg.equals("exit")){
                                    break;
                            }
                            
                            // UDP数据发送
                            SimpleDateFormat f = new SimpleDateFormat("MMM dd,yyyy kk:mm:ss");
                            String time = "现在的时间是:" + f.format(new Date());
                            System.out.println(time );
                            packet.setData(time.getBytes());
                            udpSocket.send(packet);
                            
                    }catch(Exception e){
                            e.printStackTrace();
                    }
            }
            udpSocket.close();
    }
}



3、针对直接URLHttpURLConnection

(1)GET方式

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {

	private static String URL_PATH = "http://192.168.0.102:8080/myhttptest/pro1.png";

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

	public static void saveImageToDisk() {
		InputStream inputStream = getInputStream();
		byte[] data = new byte[1024];
		int len = 0;
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream("C:\\test.png");
			while ((len = inputStream.read(data)) != -1) {
				fileOutputStream.write(data, 0, len);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 获得服务器端的数据,以InputStream形式返回
	 * @return
	 */
	public static InputStream getInputStream() {
		InputStream inputStream = null;
		HttpURLConnection httpURLConnection = null;
		try {
			URL url = new URL(URL_PATH);
			if (url != null) {
				httpURLConnection = (HttpURLConnection) url.openConnection();
				// 设置连接网络的超时时间
				httpURLConnection.setConnectTimeout(3000);
				httpURLConnection.setDoInput(true);
				// 表示设置本次http请求使用GET方式请求
				httpURLConnection.setRequestMethod("GET");
				int responseCode = httpURLConnection.getResponseCode();
				if (responseCode == 200) {
					// 从服务器获得一个输入流
					inputStream = httpURLConnection.getInputStream();
				}
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return inputStream;
	}

	public static void main(String[] args) {
		// 从服务器获得图片保存到本地
		saveImageToDisk();
	}
}

(2)POST方式

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {

	// 请求服务器端的url
	private static String PATH = "http://192.168.0.102:8080/myhttptest/servlet/LoginAction";
	private static URL url;

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

	static {
		try {
			url = new URL(PATH);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param params
	 *            填写的url的参数
	 * @param encode
	 *            字节编码
	 * @return
	 */
	public static String sendPostMessage(Map<String, String> params,
			String encode) {
		// 作为StringBuffer初始化的字符串
		StringBuffer buffer = new StringBuffer();
		try {
			if (params != null && !params.isEmpty()) {
				  for (Map.Entry<String, String> entry : params.entrySet()) {
						// 完成转码操作
						buffer.append(entry.getKey()).append("=").append(
								URLEncoder.encode(entry.getValue(), encode))
								.append("&");
					}
				buffer.deleteCharAt(buffer.length() - 1);
			}
			// System.out.println(buffer.toString());
			// 删除掉最有一个&
			
			System.out.println("-->>"+buffer.toString());
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();
			urlConnection.setConnectTimeout(3000);
			urlConnection.setRequestMethod("POST");
			urlConnection.setDoInput(true);// 表示从服务器获取数据
			urlConnection.setDoOutput(true);// 表示向服务器写数据
			// 获得上传信息的字节大小以及长度
			byte[] mydata = buffer.toString().getBytes();
			// 表示设置请求体的类型是文本类型
			urlConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			urlConnection.setRequestProperty("Content-Length",
					String.valueOf(mydata.length));
			// 获得输出流,向服务器输出数据
			OutputStream outputStream = urlConnection.getOutputStream();
			outputStream.write(mydata,0,mydata.length);
			outputStream.close();
			// 获得服务器响应的结果和状态码
			int responseCode = urlConnection.getResponseCode();
			if (responseCode == 200) {
				return changeInputStream(urlConnection.getInputStream(), encode);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 将一个输入流转换成指定编码的字符串
	 * 
	 * @param inputStream
	 * @param encode
	 * @return
	 */
	private static String changeInputStream(InputStream inputStream,
			String encode) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if (inputStream != null) {
			try {
				while ((len = inputStream.read(data)) != -1) {
					outputStream.write(data, 0, len);
				}
				result = new String(outputStream.toByteArray(), encode);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", "admin");
		params.put("password", "1234");
		String result = HttpUtils.sendPostMessage(params, "utf-8");
		System.out.println("--result->>" + result);
	}

}


(3)HttpClient

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

	public static String sendHttpClientPost(String path,
			Map<String, String> map, String encode) {
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		if (map != null && !map.isEmpty()) {
			for (Map.Entry<String, String> entry : map.entrySet()) {
				list.add(new BasicNameValuePair(entry.getKey(), entry
						.getValue()));
			}
		}
		try {
			// 实现将请求的参数封装到表单中,请求体重
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
			// 使用Post方式提交数据
			HttpPost httpPost = new HttpPost(path);
			httpPost.setEntity(entity);
			// 指定post请求
			DefaultHttpClient client = new DefaultHttpClient();
			HttpResponse httpResponse = client.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				return changeInputStream(httpResponse.getEntity().getContent(),
						encode);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 将一个输入流转换成指定编码的字符串
	 * 
	 * @param inputStream
	 * @param encode
	 * @return
	 */
	public static String changeInputStream(InputStream inputStream,
			String encode) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if (inputStream != null) {
			try {
				while ((len = inputStream.read(data)) != -1) {
					outputStream.write(data, 0, len);
				}
				result = new String(outputStream.toByteArray(), encode);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String path = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", "admin");
		params.put("password", "123");
		String result = HttpUtils.sendHttpClientPost(path, params, "utf-8");
		System.out.println("-->>"+result);
	}

}

4、使用Web ServiceAndroid可以通过开源包如jackson去支持XmlrpcJsonrpc,另外也可以用Ksoap2去实现Webservice 

<span style="color:#444444;">import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

/**
 * 在这个帮助类中,根据文档说明和URL地址
 * 先获取支持的省份信息
 * 再根据某一个省份获取城市信息
 * 再根据城市信息获取天气情况
 * 
 *
 */
public class </span><span style="color:#ff0000;">WebServiceHelper</span><span style="color:#444444;"> {
	public static final String TAG = "WebServiceHelper";
	
	// WSDL文档中的命名空间
	private static final String targetNameSpace = "http://WebXml.com.cn/";
	// WSDL文档中的URL
	private static final String WSDL = "http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";	
	// 需要调用的方法名(获得本天气预报Web Services支持的洲、国内外省份和城市信息)
	private static final String getSupportProvince = "getSupportProvince";
	// 需要调用的方法名(获得本天气预报Web Services支持的城市信息,根据省份查询城市集合:带参数)
	private static final String getSupportCity = "getSupportCity";
	// 根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数
	private static final String getWeatherbyCityName = "getWeatherbyCityName";

	/**
	 * 根据最新的文档,接口好像变了。。。囧
	 * 获得州,国内外省份和城市信息 
	 * @return
	 */
	public List<String> getProvince() {
		List<String> provinces = new ArrayList<String>();
	 
		SoapObject soapObject = new SoapObject(targetNameSpace, getSupportProvince);
		// request.addProperty("参数", "参数值");调用的方法参数与参数值(根据具体需要可选可不选)
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(soapObject);
		// envelope.bodyOut=request;
		AndroidHttpTransport httpTranstation = new AndroidHttpTransport(WSDL);
		// 或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
		
		try {
			httpTranstation.call(targetNameSpace + getSupportProvince, envelope);
			Log.i(TAG, targetNameSpace + getSupportProvince);
			
			SoapObject result = (SoapObject) envelope.getResponse();
			// 下面对结果进行解析,结构类似json对象
			Log.i(TAG, ""+result.getPropertyCount());
			int count = result.getPropertyCount();
			for (int index = 0; index < count; index++) {
				provinces.add(result.getProperty(index).toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
		
		return provinces;
	}

	/**
	 * 根据省份或者直辖市获取天气预报所支持的城市集合
	 * 比如内蒙古-->【赤峰市、呼市、包头等。。。】 
	 * @param province 
	 * @return
	 */
	public List<String> getCitys(String province) {
		List<String> citys = new ArrayList<String>();
		
		SoapObject soapObject = new SoapObject(targetNameSpace, getSupportCity);
		soapObject.addProperty("byProvinceName", province);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(soapObject);
		AndroidHttpTransport httpTransport = new AndroidHttpTransport(WSDL);
		
		try {
			httpTransport.call(targetNameSpace + getSupportCity, envelope);
			SoapObject result = (SoapObject) envelope.getResponse();
			int count = result.getPropertyCount();
			for (int index = 0; index < count; index++) {
				citys.add(result.getProperty(index).toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
		return citys;
	}

	/**
	 * 根据城市信息获取天气预报信息
	 * @param city
	 * @return
	 **/
	@SuppressWarnings("deprecation")
	public WeatherBean getWeatherByCity(String city) {
		 
		WeatherBean bean = new WeatherBean();
		
		SoapObject soapObject = new SoapObject(targetNameSpace, getWeatherbyCityName);
		city = city.substring(0,city.length()-7);
		Log.i(TAG, "city="+city); 
		soapObject.addProperty("theCityName", city);   // 调用的方法参数与参数值(根据具体需要可选可不选)
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(soapObject);
		envelope.bodyOut = soapObject;
		
		AndroidHttpTransport httpTranstation = new AndroidHttpTransport(WSDL);
		// 或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
		httpTranstation.debug = true;
		
		try {
			httpTranstation.call(targetNameSpace + getWeatherbyCityName, envelope);
			
			SoapObject result = (SoapObject) envelope.getResponse();
			if(result != null){
				Log.i(TAG, "result = " + result);
				
				// 下面对结果进行解析,结构类似json对象
				bean = parserWeather(result);
				
			}else{
				Log.i(TAG, "result = null");
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
		 
		return bean;
	}
	
	/**
	 * 测试用:根据城市名称获取天气情况
	 * @param city
	 */
	public void getWeatherByCityTest(String city){
		try {
			SoapObject msg = new SoapObject(
					"http://WebXml.com.cn/",
					"getWeatherbyCityName");
			
			city = city.substring(0,city.length()-7);
			Log.i(TAG, "city="+city); 
			msg.addProperty("theCityName", city);
			 
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.bodyOut = msg;
			envelope.dotNet = true;

			AndroidHttpTransport sendRequest = new AndroidHttpTransport(
					"http://www.webxml.com.cn/webservices/weatherwebservice.asmx");
			envelope.setOutputSoapObject(msg);
			sendRequest
					.call("http://WebXml.com.cn/getWeatherbyCityName",
							envelope);

			SoapObject result = (SoapObject) envelope.bodyIn;
			SoapObject detail = (SoapObject) result
					.getProperty("getWeatherbyCityNameResult");
			System.out.println(detail + "");

		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 测试用
	 * @param detail
	 */
	private void parseWeather(SoapObject detail) {
		String weatherToday = null,weatherTomorrow = null,weatherAfterday = null;
		int iconToday[] = null,iconTomorrow[] = null,iconAfterday[] = null;
//		String date = detail.getProperty(6).toString();
//		String weatherToday = "今天:" + date.split(" ")[0];
//		Log.i(TAG, weatherToday);
//		weatherToday = weatherToday + "\n天气:" + date.split(" ")[1];
		weatherToday = weatherToday + "\n气温:" + detail.getProperty(5).toString();
		weatherToday = weatherToday + "\n风力:" + detail.getProperty(7).toString() + "\n";
		Log.i(TAG, weatherToday);
		iconToday[0] = parseIcon(detail.getProperty(8).toString());
		iconToday[1] = parseIcon(detail.getProperty(9).toString());
		String weatherCurrent = detail.getProperty(10).toString();
		
//		date = detail.getProperty(13).toString();
//		String weatherTomorrow = "明天:" + date.split(" ")[0];
//		weatherTomorrow = weatherTomorrow + "\n天气:" + date.split(" ")[1];
		weatherTomorrow = weatherTomorrow + "\n气温:" + detail.getProperty(12).toString();
		weatherTomorrow = weatherTomorrow + "\n风力:" + detail.getProperty(14).toString() + "\n";
		iconTomorrow[0] = parseIcon(detail.getProperty(15).toString());
		iconTomorrow[1] = parseIcon(detail.getProperty(16).toString());
		
//		date = detail.getProperty(18).toString();
//		String weatherAfterday = "后天:" + date.split(" ")[0];
//		weatherAfterday = weatherAfterday + "\n天气:" + date.split(" ")[1];
		weatherAfterday = weatherAfterday + "\n气温:" + detail.getProperty(17).toString();
		weatherAfterday = weatherAfterday + "\n风力:" + detail.getProperty(19).toString() + "\n";
		iconAfterday[0] = parseIcon(detail.getProperty(20).toString());
		iconAfterday[1] = parseIcon(detail.getProperty(21).toString());
		} 


	/**
	 * 解析返回的结果 
	 * @param soapObject
	 **/
	protected WeatherBean parserWeather(SoapObject soapObject) {
		WeatherBean bean = new WeatherBean();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		List<Integer> icons = new ArrayList<Integer>();
		
		// 城市名
		bean.setCityName(soapObject.getProperty(1).toString());
		// 城市简介
		bean.setCityDescription(soapObject.getProperty(
				soapObject.getPropertyCount() - 1).toString());
		// 天气实况+建议
		bean.setLiveWeather(soapObject.getProperty(10).toString() + "\n"
				+ soapObject.getProperty(11).toString());
		// 其他数据
		//日期,
		String date = soapObject.getProperty(6).toString();
		
		Log.i(TAG, "");
		// ---------------------------------------------------
		String weatherToday = "今天:" + date.split(" ")[0];
		weatherToday += "\n天气:" + date.split(" ")[1];
		weatherToday += "\n气温:" + soapObject.getProperty(5).toString();
		weatherToday += "\n风力:" + soapObject.getProperty(7).toString();
		weatherToday += "\n";
 
		icons.add(parseIcon(soapObject.getProperty(8).toString()));
		icons.add(parseIcon(soapObject.getProperty(9).toString()));
		map.put("weatherDay", weatherToday);
		map.put("icons", icons);
		list.add(map);
		
		// -------------------------------------------------
		map = new HashMap<String, Object>();
		date = soapObject.getProperty(13).toString();
		String weatherTomorrow = "明天:" + date.split(" ")[0];
		weatherTomorrow += "\n天气:" + date.split(" ")[1];
		weatherTomorrow += "\n气温:" + soapObject.getProperty(12).toString();
		weatherTomorrow += "\n风力:" + soapObject.getProperty(14).toString();
		weatherTomorrow += "\n";
		icons = new ArrayList<Integer>();
		icons.add(parseIcon(soapObject.getProperty(15).toString()));
		icons.add(parseIcon(soapObject.getProperty(16).toString()));
		map.put("weatherDay", weatherTomorrow);
		map.put("icons", icons);
		list.add(map);
		
		// --------------------------------------------------------------
		map = new HashMap<String, Object>();
		date = soapObject.getProperty(18).toString();
		String weatherAfterTomorrow = "后天:" + date.split(" ")[0];
		weatherAfterTomorrow += "\n天气:" + date.split(" ")[1];
		weatherAfterTomorrow += "\n气温:" + soapObject.getProperty(17).toString();
		weatherAfterTomorrow += "\n风力:" + soapObject.getProperty(19).toString();
		weatherAfterTomorrow += "\n";
		icons = new ArrayList<Integer>();
		icons.add(parseIcon(soapObject.getProperty(20).toString()));
		icons.add(parseIcon(soapObject.getProperty(21).toString()));
		map.put("weatherDay", weatherAfterTomorrow);
		map.put("icons", icons);
		list.add(map);
		
		// 把解析后的数据放到一个list中
		bean.setList(list); 
		return bean;
	}

	// 解析图标字符串
	private int parseIcon(String data) {
		// 0.gif,返回名称0,
		int resID = 32;
		String result = data.substring(0, data.length() - 4).trim();
		// String []icon=data.split(".");
		// String result=icon[0].trim();
		// Log.e("this is the icon", result.trim());
		if (!result.equals("nothing")) {
			resID = Integer.parseInt(result.trim());
		}
		return resID;
		// return ("a_"+data).split(".")[0];
	}
}</span>

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;

/**
 * 这个是使用另一种方式获取信息,主要是书写代码的方式不同
 * @author Song Shi Chao
 *
 */
public class WebServiceUtil {
	// 命名空间
	private static final String serviceNameSpace = "http://WebXml.com.cn/";
	// 请求URL
	private static final String serviceURL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
	// 调用方法(获得支持的城市)
	private static final String getSupportCity = "getSupportCity";
	// 调用城市的方法(需要带参数)
	private static final String getWeatherbyCityName = "getWeatherbyCityName";
	// 调用省或者直辖市的方法(获得支持的省份或直辖市)
	private static final String getSupportProvince = "getSupportProvince";

	/**
	 * @return城市列表 
	 */
	public static List<String> getCityList() {
		// 实例化SoapObject对象
		SoapObject request = new SoapObject(serviceNameSpace, getSupportCity);
		// 获得序列化的Envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.bodyOut = request;
		(new MarshalBase64()).register(envelope);
		// Android传输对象
		AndroidHttpTransport transport = new AndroidHttpTransport(serviceURL);
		transport.debug = true;
		// 调用
		try {
			transport.call(serviceNameSpace + getWeatherbyCityName, envelope);
			if (envelope.getResponse() != null) {
				return parse(envelope.bodyIn.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static List<String> getProviceList() {
		// 实例化SoapObject对象
		SoapObject request = new SoapObject(serviceNameSpace,
				getSupportProvince);
		// 获得序列化的Envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.bodyOut = request;
		(new MarshalBase64()).register(envelope);
		// Android传输对象
		AndroidHttpTransport transport = new AndroidHttpTransport(serviceURL);
		transport.debug = true;
		// 调用
		try {
			transport.call(serviceNameSpace + getWeatherbyCityName, envelope);
			
			if (envelope.getResponse() != null) {
				return null;
			}
		} catch (IOException e) { 
			e.printStackTrace();
		} catch (XmlPullParserException e) { 
			e.printStackTrace();
		}
		return null;
	}
 
	/**
	 * @param cityName
	 * @return
	 */
	public static String getWeather(String cityName) {
		return "";
	}

	/**
	 * 解析XML
	 */
	private static List<String> parse(String str) {
		String temp;
		List<String> list = new ArrayList<String>();
		if (str != null && str.length() > 0) {
			int start = str.indexOf("string");
			int end = str.lastIndexOf(";");
			temp = str.substring(start, end - 3);
			String[] test = temp.split(";");
			for (int i = 0; i < test.length; i++) {
				if (i == 0) {
					temp = test[i].substring(7);
				} else {
					temp = test[i].substring(8);
				}
				int index = temp.indexOf(",");
				list.add(temp.substring(0, index));
			}
		}
		return list;
	}

	/**
	 * 获取天气
	 * @param soapObject
	 **/
	private void parseWeather(SoapObject soapObject) {
		// String date=soapObject.getProperty(6);
	}
}


/**
 * 封装天气情况的JAVA BEAN
 * 
 * @author Song Shi Chao
 *
 */
public class WeatherBean {
	// 城市名
	public String cityName;
	// 城市简介
	public String cityDescription;
	// 天气实况+建议
	public String liveWeather;
	
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
	public String getCityDescription() {
		return cityDescription;
	}
	public void setCityDescription(String cityDescription) {
		this.cityDescription = cityDescription;
	}
	public String getLiveWeather() {
		return liveWeather;
	}
	public void setLiveWeather(String liveWeather) {
		this.liveWeather = liveWeather;
	}
	
	public void setList(List<Map<String, Object>> list) { 
		Map<String, Object> map = new HashMap<String, Object>();
		for(int i=0; i<list.size(); i++){
			 map = list.get(i);
			 WeatherBean w = new WeatherBean();
			 Object o = map.get("weatherDay");
			 System.out.println(o.toString());
		}
		
		
	}
	
}


对应界面类

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

public class WeatherInfoActivity extends TabActivity implements
		OnTabChangeListener {
	public static final String TAG = "WeatherInfoActivity";
	WebServiceHelper wsh;
	WeatherBean bean = new WeatherBean();
	TabHost mTabHost;
	String city;

	TextView txt1, txt2, txt3;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.weatherinfo);

		Intent i = this.getIntent();
		if (i != null) {
			Bundle bd = i.getExtras();
			if (bd != null) {
				if (bd.containsKey("city")) {
					city = bd.getString("city");
				}
			}
		}

		mTabHost = getTabHost();
		// 设置容器的背景色
		mTabHost.setBackgroundColor(Color.argb(150, 22, 70, 150));

		mTabHost.addTab(mTabHost
				.newTabSpec("one")
				.setIndicator("天气", getResources().getDrawable(R.drawable.icon))
				.setContent(R.id.lin1));
		mTabHost.addTab(mTabHost
				.newTabSpec("two")
				.setIndicator("天气情况",
						getResources().getDrawable(R.drawable.icon))
				.setContent(R.id.textview2));
		mTabHost.addTab(mTabHost
				.newTabSpec("three")
				.setIndicator("城市信息",
						getResources().getDrawable(R.drawable.icon))
				.setContent(R.id.textview3));

		mTabHost.setCurrentTab(0);

		mTabHost.setOnTabChangedListener(this);

		Button btn1 = (Button) this.findViewById(R.id.button1);
		btn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new Thread() {
					public void run() {
						try {
							SoapObject msg = new SoapObject(
									"http://WebXml.com.cn/",
									"getWeatherbyCityName");
							msg.addProperty("theCityName", city);

							SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
									SoapEnvelope.VER11);
							envelope.bodyOut = msg;
							envelope.dotNet = true;

							AndroidHttpTransport sendRequest = new AndroidHttpTransport(
									"http://www.webxml.com.cn/webservices/weatherwebservice.asmx");
							envelope.setOutputSoapObject(msg);
							sendRequest
									.call("http://WebXml.com.cn/getWeatherbyCityName",
											envelope);

							SoapObject result = (SoapObject) envelope.bodyIn;
							SoapObject detail = (SoapObject) result
									.getProperty("getWeatherbyCityNameResult");
							System.out.println(detail + "");

						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}.start();

			}

		});
	}

	public void init() {
		txt1 = (TextView) this.findViewById(R.id.textview1);
		txt2 = (TextView) this.findViewById(R.id.textview2);
		txt3 = (TextView) this.findViewById(R.id.textview3);
	}

	@Override
	public void onTabChanged(String tabId) {
		WebServiceHelper wsh = new WebServiceHelper();

		// 如果是天气选项卡,就获取天气
		if (tabId.equals("one")) {

			// SimpleAdapter adapter = new SimpleAdapter(this, weather_list_map,
			// R.layout.listview_item,
			// new String[]{"weatherDay","icons"},
			// new int[]{R.id.info_weather,R.id.image_weather});
			// mListView_weather.setAdapter(adapter);
			
		}

		// 如果是天气情况选项卡,就获取天气情况
		if (tabId.equals("two")) {
			wsh.getWeatherByCityTest(city);

		}

		// 如果是城市信息选项卡,就获取城市信息
		if (tabId.equals("three")) {
			bean = wsh.getWeatherByCity(city);
			

			String liveWeather = bean.getLiveWeather(); // 天气
			String cityDes = bean.getCityDescription();
			String cityInfo = bean.getCityName(); // 城市信息

			Log.i(TAG, "liveWeather = " + liveWeather);
			Log.i(TAG, "cityDes = " + cityDes);
			Log.i(TAG, "cityInfo = " + cityInfo);
			
		}

	}

}

对应xml布局:

<?xml version="1.0" encoding="utf-8"?> 
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 
<LinearLayout 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 
<TabWidget 
android:id="@android:id/tabs" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" /> 
	<FrameLayout 
	android:id="@android:id/tabcontent" 
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent"> 
	
	<LinearLayout
	android:id="@+id/lin1" 
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent" >
	<Button
	android:id="@+id/button1" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content" 
	android:text="button"
	></Button>
	<TextView 
	android:id="@+id/textview1" 
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent" 
	android:text="this is one tab" /> 
	
	</LinearLayout>
	<TextView 
	android:id="@+id/textview2" 
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent" 
	android:text="this is two tab" /> 
	
	<TextView 
	android:id="@+id/textview3" 
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent" 
	android:text="this is third tab" /> 
	
	</FrameLayout> 
</LinearLayout> 
</TabHost> 


import java.util.ArrayList;
import java.util.List;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ProvinceActivity extends Activity {
	public static final String TAG = "ProvinceActivity";
	WebServiceHelper wsh = new WebServiceHelper();
	public ProvinceAdapter provinceAdapter;
	public List<String> provinces = new ArrayList<String>();
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.province);
        
        ListView province = (ListView) this.findViewById(R.id.proviceList);
        
        provinces = wsh.getProvince();
        provinceAdapter = new ProvinceAdapter();
        Log.i(TAG, ""+provinces);
        province.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) { 
				Object obj = view.getTag();
				Log.i(TAG, ""+view.getTag());
				if (obj != null) {
					String id1 = obj.toString();
					Log.i(TAG, ""+ obj.toString());
					Intent intent = new Intent(ProvinceActivity.this, CityActivity.class);
					Bundle b = new Bundle();
					b.putString("province", id1);
					intent.putExtras(b);
					startActivity(intent);
				}
				
			}
        	
        });
        province.setAdapter(provinceAdapter);
    }
	
	class ProvinceAdapter extends BaseAdapter {

		@Override
		public int getCount() { 
			return provinces.size();
		}

		@Override
		public Object getItem(int position) { 
			return provinces.get(position);
		}

		@Override
		public long getItemId(int position) { 
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			//下面俩种方法都可以
			// LayoutInflaterinflater=getLayoutInflater();
			//LayoutInflaterinflater=(LayoutInflater)mContext.getSystemServic(LAYOUT_INFLATER_SERVICE);

			LayoutInflater mInflater = getLayoutInflater(); 
			convertView =  mInflater.inflate(R.layout.province_item, null);
			TextView tv = (TextView) convertView.findViewById(R.id.proviceText);
			tv.setText(provinces.get(position));
			convertView.setTag(tv.getText());
		 
			return convertView;
		}
		
	}
}

对应xml:

<?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"
    >

	<ListView
	android:id="@+id/proviceList"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content">
	</ListView>
</LinearLayout>

import java.util.ArrayList;
import java.util.List;

import com.parabola.main.ProvinceActivity.ProvinceAdapter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class CityActivity extends Activity { 
	public static final String TAG = "CityActivity";
	String city = null;
	WebServiceHelper wsh = new WebServiceHelper();
	List<String> citys = new ArrayList<String>();
	CityAdapter cityAdapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.city);
        
        ListView cityList = (ListView) this.findViewById(R.id.cityList);
        
        Intent i = this.getIntent();
        if(i != null){
        	Bundle bd = i.getExtras();
        	if(bd != null){
        		if(bd.containsKey("province")){
        			city = bd.getString("province");
        		}
        	}
        }
        
        citys = wsh.getCitys(city);
        cityAdapter = new CityAdapter();
         
        cityList.setOnItemClickListener(new OnItemClickListener(){ 
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Object obj = view.getTag(); 
				if (obj != null) {
					String id1 = obj.toString();
					Log.i(TAG, ""+ obj.toString());
					Intent intent = new Intent(CityActivity.this, WeatherInfoActivity.class);
					Bundle b = new Bundle();
					b.putString("city", id1);
					intent.putExtras(b);
					startActivity(intent); 
				}
			}
		});
        
        cityList.setAdapter(cityAdapter);
         
    }
    
    class CityAdapter extends BaseAdapter {

		@Override
		public int getCount() { 
			return citys.size();
		}

		@Override
		public Object getItem(int position) { 
			return citys.get(position);
		}

		@Override
		public long getItemId(int position) { 
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) { 
			LayoutInflater mInflater = getLayoutInflater(); 
			convertView =  mInflater.inflate(R.layout.province_item, null);
			TextView tv = (TextView) convertView.findViewById(R.id.proviceText);
			tv.setText(citys.get(position));
			convertView.setTag(tv.getText());
			return convertView;
		}
    	
    }
}

对应XML:

<?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:id="@+id/proviceText"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:text="City">
	</TextView>
	<ListView
	android:id="@+id/cityList"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content">
	</ListView>
</LinearLayout>


5、直接使用WebView视图组件显示网页。基于WebView 进行开发,Google已经提供了一个基于chrome-liteWeb浏览器,直接就可以进行上网浏览网页。




android网络通信方式总结

标签:网络   通信   android   

原文地址:http://blog.csdn.net/u014600432/article/details/41647287

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!