网络通信

来源:互联网 发布:手机mac地址修改 编辑:程序博客网 时间:2024/05/17 03:03

(written in  2012-08-09 22:29:46


无线网络类型

  • 无线广域网WWAN
  • 无线城域网WMAN
  • 无线局域网WLAN
  • 无线个域网WPAN
  • 低速率无线个域网LR-WPAN

 

网络相关的接口

  • java.net.*

try{//定义地址URL url = new URL("http://www.google.com");HttpURLConnection http = (HttpURLConnection) url.openConnection();//得到连接状态int nRC = http.getResponseCode();if(nRC == HttpURLConnection.HTTP_OK){//取得数据InputStream is = http.getInputStream();//处理数据}}catch(Exception e){}


  • org.apache.*

try{//创建HttpClient//这里使用DefaultHttpClient表示默认属性HttpClient hc = new DefaultHttpClient();//HttpGet实例HttpGet get = new HttpGet("http://www.google.com");//连接HttpRespone rp = hc.execute(get);if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK){InputStream is  = rp.getEntity().getContent();}}catch(Exception e){}


  • android.net.*

try{//ip地址InetAddrass inetAddress = InetAddress.getByName("192.168.1.110");//端口Socekt client = new Socket(inetAddress,61203,true);//取得数据InputStream in  = client.getInputStream();OutputStream out = client.getOutputStream();\//处理数据。。。put.close();in.close();client.close(); }catch(UnknownHostException e){……}catch(IOException e){……} 


HTTP通信

HttpURLConnection接口

例:GET方式

public class Acitvity02 extends Activity{private final String DEBUG_TAG = "Activity02"; public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.http); TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);//http地址String httpUrl = "http://192.168.1.110:8080/http1.jsp?par=abc";//获取数据String resultData = "";URL url = null;try{//构造一个URL对象url = new URL(httpUrl);}catch(MalformedURLException e){Log.e(DEBUG_TAG,"MalformedURILException");}if(url != null){try{//使用HttpConnection打开连接HttpURLConnection urlConn = (HttpURLConnection)url.openCounnection();//得到读取的内容InputStreamReader in = new InputStreamReader(urlConn.getInputStream());//输出创建BufferedReaderBufferedReader buffer = new BufferedReader(in);String inputLine = null;//使用循环来读取获得的数据while(((inputLine = buffer.readLine() != null)){resultData += inputLine + "\n";}in.close();urlConn.disconnect(); //设置显示内容if(resultData ! = null){mTextView.setTextView(resultData);}else{mTextView.setTextView("读取的内容为NULL");}}catch(IOException e){Log.e(DEBUG_TAG,"IOException");}}else{Log.e(DEBUG_TAG,"Url NULL");} //设置按键事件Button button_back = (Button)findViewById(R.id.Button_back);button_back.setOnClickListener(new Button.onClickListener(){public void onClick(View v){Intent intent = new Intent();intent.setClass(Activity02.this,Activity01.class);startActivity(intent);Activity02.this.finish();}}); }}


 

例:POST方式

public class Activity04 extends Activity{ private fianl String DEBUG_TAG  = "test"; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstancedState);setContentView(R.layout.http); TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);String httpUrl = "http://192.168.1.110:8080/httpget.jsp";String resultData = "";URL url = null;try{url = new URL(httpUrl);}catch(MalformedURLException e){Log.e(DEBUG_TAG,"MalformedURLException");} if(url != null){try{HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();urlConn.setDoOutput(true);urlConn.setDoInput(true);urlConn.setRequestMethod("POST");urlConn.setUseCached(false);urlConn.setInstanceFollowRedirects(true); urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());String content = "par=" + URLEncoder.encode("ABCDEFG","gb2312");//将要上传的内容写入out.writeBytes(conent);out.flush();out.close(); //获取数据BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));String inputLine = null;while(((inputLine = reader.readLine()) != null)){resultData += inputLine + "\n";}reader.close();urlConn.disconnect();if(resultData != null){mTextView.setText(resultData);}else{mTextView.setText("读取的内容为NULL");}}catch(IOException e){Log.e(DEBUG_TAG,"IOException");}}else{Log.e(DEBUG_TAG,"Uri NULL");} Button button_Back = (Button)findViewById(R.id.Button_Back);button_Back.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){Intent intent = new Intent();intent.setClass(Activity04.this,Activity01.class);startActivity(intent);Activity04.this.finish();}});}}


 

显示网络上的图片

 

public Bitmap GetNetBitmap(String url){URL imageUrl  = null;Bitmap bitmap = null;try{imageUrl = new URL(url);}catch(MalformedURLException e){Log.e(DEBUG_TAG,e.getMessager());} try{HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();conn.setDoInput(true);conn.connect();InputStream is = conn.getInputStream();bitmap = BitmapFactory.decodeStream(is);is.close();}catch(IOException e){Log.e(DEBUG_TAG,e.getMessage();}return bitmap;}


 

HttpClient接口

抽象方法

ClientConnectionManager

关闭所有无效,超时的连接

closeIdleConnections

关闭空闲的连接

releaseConnection

释放一个连接

requestConnection

请求一个新的连接

Shudown

关闭管理器并释放资源

例:GET方式

public class Activity02 extends Activity{public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.http); TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);String httpUrl="http://192.168.1.110:8080/httpget.jsp?=par=HttpClient_android_Get"; //连接对象HttpGet httpRequest = new HttpGet(httpUrl);try{HttpClient httpclient = new DefaultHttpClient();HttpResponse httpResponse = httpclient.execute(httpRequest);//请求成功if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){String strResult = EntityUtils.toString(httpResponse.getEntity());mTextView.setView(strResult);}else{mTextView.setText("请求错误!");}}catch(ClientProtocolException e){mTextView.setText(e.getMessage().toString());}catch(IOException e){mTextView.setText(e.getMessage().toString());}catch(Exception e){mTextView.setText(e.getMessage().toString());} //设置按讲事件监听Button button_Back = (Button)findViewById(R.id.Button_Back);button_Back.setOnClickListener(new Button.OnClickListener(){public void onClick(View v){Intent intent = new Intent();intent.setClas(Activity02.this,Activity01.class);startActivity(intent);Activity02.this.finish();}});}}


 

例:POST方式

public class Activity03 extends Activity{public void onCreate(Bundle savedInstance){super.onCreate(savedInstance);setContentView(R.layout.http); TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);String httpUrl = "http://192.168.1.110:8080/httpget.jsp";//连接对象HttpPost httpRequest = new HttpPost(httpUrl);//使用NameValuePair来保存还要传递的post参数List<NameValuePair> params = new ArrayList<NameValuePair>();//添加要传递的参数params.add(new BasicNameValuePair("par","HttpClient_android_Post"));try{//设置字符集HttpEnity httpentity = new UrlEncodedFormEntity(params,"gb2312");//请求httpRequest.setEnity(httpentity);HttpClient httpclient = new DefaultHttpClient();HttpResponse httpResponse  = httpResponse.execute(httpRequest);if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//取得返回的字符串String strResult = EntityUtils.toString(httpResponse.getEntity());mTextView.setText(strResult);}else{mTextView.setText("请求错误!");}}catch(ClientProtocolException e){mTextView.setText(e.getMessage().toString());}catch(IOException e){mTextView.setText(e.getMessage().toString());}catch(Exception e){mTextView.setText(e.getMessage().toString());} //监听事件Button button_Back = (Button)findViewById(R.id.Button_Back);button_Back.setOnClickListener(new Button.OnClickListener()){public void onClick(View v){Intent intent = new Intent();intent.setClass(Activity03.this,Activity01.class);startActivity(intent);Activity03.this.finish();}});}}


 

实时更新

例:

public class Activity01 extend Activity{private final String DEBUG_TAG = "Activity02";private TextView mTextView;private Button mButton; public void onCreate(Bundle savedInstanceState){super.onCreate(saveInstanceState);setContentView(R.layout.main); mTextView = (TextView)this.findViewById(R.id.TextView01);mButton = (Button)this.findViewById(R.id.Button01);mButton.setOnClickListener(new Button.OnClickListener(){public void onClick(View v){refresh();}}); new Thread(mRunnable).start();} private void refresh(){String httpUrl = "http://192.168.1.110:8080/date.jsp";String resultData = "";URL url = null;try{url = new URL(httpUrl);}catch(MalformedURLException e){Log.e(DEBUG_TAG,"MalformedURLException");} if(url != null){try{HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();InputStreamReader in = new InputStreamReader(urlConn.getInputStream());BufferedReader buffer = new BufferedReader(in);String inputLine = null; //使用循环来读取获得数据while(((inputLine = buffer.readLine())!=null){resultData += inputLine +"\n";} in.close();urlConn.disconnect();if(resultData !=null){mTextView.setText(resultData);}else{mTextView.setText("读取内容为null");}}catch(IOException e){Log.e(DEBUG_TAG,"IOException");}}else{Log.e(DEBUG_TAG,"Url NULL");}} private Runnalbe mRunnable = new Runnable(){ public void run(){while(true){try{Thread.sleep(5*1000);mHandler.sendMessage(mHandler.obtainMessage());}catch(InterruptedException e){Log.e(DEBUG_TAG,e.toString());}}}}; Handler mHandler = new Handler(){public void handleMessage(Message msg){super.handleMessage(msg);refresh();}};}


 

Socket通信(套件字)

端口号最好大于1023,否和可能跟默认的其他服务端口号冲突。

例:服务器

public class Server implements Runnable{public void run(){try{//创建ServerSocketServerSocket serverSock = new ServerSocket(54321);while(true){//等待接收客户端的请求Socket client = serverSocket.accept();System.out.println("accept");try{//接收客户端的消息BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));String str = in.readLine();//向服务器发送消息PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);out.println("server message");//关闭流in.close();out.close(); }catch(Exception e){e.printStackTrance();}finally{client.close();}}}catch(Exception e){e.printStackTrance();}} //开启服务器public static void main(String[] a){Thread desktopServerThread = new Thread(new Server());desktopServerThread.start();}} 


例:客户端

public class Activity01 extends Activity{private final String DEBUG_TAG = "Activity01"; private TextView mTextView = null;private EditText mEditText = null;private Button mButton = null; public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main); mButton = (Button)findViewById(R.id.BUtton01);mTextView = (TextView)findViewById(R.id.TextView01);mEditText = (EditText)findViewById(R.id.EditText01); //登录mButton.setOnClickListener(new OnClickListener(){public void onClick(View v){Socket socket = null;String message = mEditText.getText().toString()+"\r\n";try{//创建Socketsocket = new Socket("192.168.1.110",54321);//向服务器发送消息PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()),true);out.println(message); //接收来自服务器的消息BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));String msg = br.readLine(); if(msg != null){mTextView.setText(msg);}else{mTextView.setView("数据错误!");} //关闭流out.close();br.close();socket.close(); }catch(Exception e){Log.e(DEBUG_TAG,e.toString());}}});}}


 

例:聊天工具

服务器

public class Server{private static final int SERVERPORT = 54321;//客户端连接private static List<Socket> mClientList = new ArrayList<Socket>();//线程池private ExecutorService mExcutorService;private ServierSocket mServerSocket; public static void main(String[] args){new Socket();} public Socket(){try{//设置服务端口mServerSocket = new ServerSocket(SERVERPORT);mExcutorService = Excutors.newCachedThreadPool(); //设置临时存放客户端连接的对象Socket client = null;while(true){//接收客户端连接并添加到list中client = mServiceSocket.accept();mClientList.add(client);//开启一个客户端的线程mExecutorService.execute(new ThreadServer(client));}}catch(IOException e){e.printStackTrace();}} //每个客户端一个线程static class ThreadServer implements Runnable{private Socket mSocket;private BufferedReader mBufferedReader;private PrintWriter mPrintWriter;private String mStrMSG; public ThreadServer(Socket socket) throws IOException{this.mSocket = socket;mBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));mStrMSG = "user:"+this.mSocket.getInetAddresss()+"come total:"+mClientList.size();sendMessage();} public void run(){try{while((mStrMSG = mBufferedReader.readLine()!=null){if(mStrMSG.trim().equals("exit")){//当一个客户端退书mClientList.remove(mSocket);mBufferedReader.close();mPrintWriter.close();sendMessage();break;}else{mStrMSG = mSocket.getInetAddress()+":"+mStrMSG;sendMessage();}}}catch(IOException e){e.printStackTrace();} private void sendMessage() throws IOException{System.out.println(mStrMSG);for(Scoket client : mClientList){mPrintWirter = new PrintWriter(client.getOutputStream(),true);mPrintWriter.println(mStrMSG);}}}} }


 

客户端

public class Activity01 extends Activity{private final String DEBUG_TAG = "Activity01"; private static final String SERVERIP = "192,168.1.110";private static final int SERVERPORT = 54321;private Thread mThread = null;private Socket mSocket = null;private Button mButton_In = null;private EditText mEditText01 = null;private EditText mEditText02 = null;private BufferedReader mBufferedReader = null;private PrintWriter mPrintWriter = null;private String mStrMSG = ""; public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);mButton_in = (Button)findViewById(R.id.Button_In);mButton_Send = (Button)findViewById(R.id.Button_Send);mEditText01 = (EditText)findViewById(R.id.EditText01);mEditText02 = (EditText)findViewById(R.id.EditText02); //登录mButton_In.setOnClickListener(new OnClickListener(){public void onClick(View v){try{mSocket = new Socket(SERVERIP,SERVERPORT);mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getOutputStream()));mPrintWriter = new PrintWriter(mSocket.getOutputStream(),true);}catch(Exception e){Log.e(DEBUG_TAG,e.toString());}}});//发送消息mButtuon_Send.setOnClickListener(new OnClickListener()){public void onClick(View v){try{//取得编辑框中输入的尼日个噢你String str = mEditext02.getText().toString()+"\n";//发送给服务器mPrintWriter.print(str);mPrintWriter.flush(); }catch(Exception e){Log.e(DEBUG_TAG,e.toString());}}}); mThread = new Thread(mRunnable);mThread.start();} //监听无夫妻发来的消息private Runnable mRunnable = new Runnable(){public void run(){while(true){tyr{if((mStrMSG = mBufferedReader.readLine()) != null){//消息换行mStrMSG += "\n";mHandler.sendMessage(mHandler.obtainMessage());}}catch(Exception e){Log.e(DEBUG_TAG,e.toString());}}}}; Handler mHandler = new Hnadler(){public void handlerMessage(Message msg){super.handleMessage(msg); try{//将聊天记录添加进来mEditText01.append(mStrMSG);}catch(Exception e){Log.e(DEBUG_TAG,e.toString());}}}}



0 0
原创粉丝点击