Java网络编程接口:
Java的网络通信有有两种的实现的方式,一种是基于套接字的方式,另外一种是基于HTTP的方式
基于套接字的方式:
tcp方式:客户端发起通信之前,必须知道服务器的IP地址或者域名。
服务器端:服务器的套接字通过ServerSocket实现,通过ServerSocket可以直接绑定端口,监听该端口传来的消息。通过ServerSocket的accept()方法可以传入该链接请求创建Socket实例,并将已经成功连接的Socket实例返回给服务器套接字,如果没有连接请求,accept() 方法将阻塞等待。通过Socket的getInputStreame()方法可以获得输入流,查看传入的消息;通过Socket的getOutputStreame()方法可以响应客户端。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ServerSocket seversocket=null;
try {
seversocket=new ServerSocket(1234);
Socket socket=seversocket.accept();
InputStream inputStream=socket.getInputStream();
OutputStream outputStream=socket.getOutputStream();
outputStream.write("ok".getBytes());//返回OK
byte buffer[]=new byte[1024*4];
int temp=0;
while ((temp=inputStream.read(buffer))!=-1) {
System.out.println(new String(buffer,0,temp));
}
} catch (Exception e) {
// TODO: handle exception
}
try {
seversocket.close();
inputStreame.close();
outputStreame.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:可以设置代理,服务器域名,服务器IP地址,端口等信息
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Socket socket=new Socket("192.168.159.1",1234);
// InputStream inputStream=new FileInputStream("C://Users/zuozhiyu/Desktop/jianli.txt");
OutputStream outputStream=socket.getOutputStream();
InputStream inputStream=socket.getInputStream();
String string="abcd";
byte buffer[]=new byte[4*1024];
buffer=string.getBytes();
int temp=0;
// while ((temp=inputStream.read(buffer))!=-1) {
// outputStream.write(buffer, 0, temp);
// }
// outputStream.flush();
outputStream.write(buffer, 0, temp);
String s=inputStream.readUTF();//读取响应的消息
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
inputStream.close();
outputStream.close;
socket.close();
}
}
基于UDP协议的套接字
基于UDP的套接字主要是通过DatagramSocket进行的,DatagramSocket在通信两端均适用,通过DatagramSocket可以绑定IP地址和端口等
DatagramSocket对象通过send()方法发送消息,通过Receive()方法接收消息,通过connect()方法建立和服务器的连接。
服务器端:主要用来接收数据
try {
DatagramSocket ds1=new DatagramSocket(8000);
byte [] buffer=new byte[1024];
DatagramPacket dp=new DatagramPacket(buffer, 1024);
ds1.receive(dp);
ds1.close();
} catch (Exception e) {
// TODO: handle exception
}
客户端:主要用来发送数据
try {
DatagramSocket ds2=new DatagramSocket();
String str="this is datagramSocket";
DatagramPacket dp2=new DatagramPacket(str.getBytes(), str.length(),InetAddress.getByName("localhost"),8000);
ds2.send(dp2);
ds2.close();
} catch (Exception e) {
// TODO: handle exception
}
Apache网络编程接口:
在Apache中,主要通过HttpClient执行HTTP通信。通过HttpResponse获取服务器响应
执行get请求
public class getThread extends Thread {
@Override
public void run() {
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet("http://www.baidu.com/");
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
int statusCode=httpResponse.getStatusLine().getStatusCode();
if (statusCode>=200&&statusCode<400) {
StringBuilder stringBuilder=new StringBuilder();
BufferedReader reader=new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),HTTP.UTF_8));
for (String s=reader.readLine();s!=null;s=reader.readLine()) {
stringBuilder.append(s);
}
reader.close();
getString=stringBuilder.toString();
handler.sendMessage(handler.obtainMessage(1));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
执行post请求:
public class PostThread extends Thread {
@Override
public void run() {
List<NameValuePair> formparams =new ArrayList<NameValuePair>(); //使用NameValuePair来保存要传递的Post参数
formparams.add(new BasicNameValuePair("username", "hello")); //添加要传递的参数
// formparams.add(new BasicNameValuePair("password", "eoe"));
HttpClient httpClient=new DefaultHttpClient();
HttpResponse httpResponse;
try {
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
HttpPost httpPost=new HttpPost("http://www.baidu.com/");
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
int statusCode=httpResponse.getStatusLine().getStatusCode();
if (statusCode>=200&&statusCode<400) {
StringBuilder stringBuilder=new StringBuilder();
BufferedReader reader=new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),HTTP.UTF_8));
for (String s=reader.readLine();s!=null;s=reader.readLine()) {
stringBuilder.append(s);
}
reader.close();
getString=stringBuilder.toString();
handler.sendMessage(handler.obtainMessage(2));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Android网络编程接口:
Android的网络接口是针对Apache的在封装和简化,目前Android支持RTP、SIP、HTTP、WIFI、SSL、代理等网络协议。
Android的HTTP通信和Apache的不同点主要体现在HttpClient的实现上,Android的HTTP通信主要是通过AndroidHttpClient而非DefaultHttpClient和Apache的HttpGet、HttpPost、HttpResponse等来实现的,通过AndroidHttpClient可以创建一个HttpClient。通过HttpGet可以获取URI的信息,自动处理服务器的重定向;通过HttpResponse可以处理服务器的响应。
try {
AndroidHttpClient client=AndroidHttpClient.newInstance(userAgent);
HttpGet httpGet=new HttpGet("www.baidu.com");
HttpResponse response=client.execute(httpGet);
if (response.getStatusLine().getStatusCode()==HttpStatus.SC_OK) {//200
//响应
}
client.close();
} catch (Exception e) {
// TODO: handle exception
}
RTP协议:实时传输协议(Real-time Transport Protocol)