HTTP
服务器端用PHP写一个模拟用户名密码验证request.php
<?php
if($_GET['username']!=null){
$username=$_GET['username'];
$pwd=$_GET['pwd'];
if($username=='abc'&&$pwd='123')
echo "Congratulations! FROM GET";
else
echo "Sorry! FROM GET";
}
else if($_POST['username']!=null){
$username=$_POST['username'];
$pwd=$_POST['pwd'];
if($username=='abc'&&$pwd='123')
echo "Congratulations! FROM POST";
else
echo "Sorry! FROM POST";
}
?>
手机客户端上:
记得在Manifest文件中添加上可以访问INTERNET的权限
用GET方式发送请求:
//生成Http客户端对象
HttpClient httpClient=new DefaultHttpClient();
//生成HttpGet对象
HttpGet httpGet=new HttpGet("http://192.168.1.92/request.php?username=abc&pwd=123"); //GET方式用?开始写键值对参数,用&隔开
//客户端执行Http Get请求使用HttpResponse相应对象来接收
HttpResponse httpResponse=httpClient.execute(httpGet);
//生成一个实体从httpRespon中获得结果
HttpEntity httpEntity=httpResponse.getEntity();
//从http实体中取出想要的信息
InputStream inputStream=httpEntity.getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
String res="";
String line="";
while((line=br.getLine())!=null){
res+=line;
}
Log.i("The Result from Server",res);
用POST方式进行请求
//生成Http客户端对象
HttpClient httpClient=new DefaultHttpClient();
//POST方式与GET方式不同在于并不显示的进行参数的传递,而是把参数放在httpEntity中进行请求
//首先生成带参数的httpEntity
NameValuePair p1=new BasicNameValuePair("username","abc"); //NameValuePair是Apache封装的键值对类
NameValuePair p2=new BasicNameValuePair("pwd","123");
List<NameValuePair> parameters=new ArrayList<NameValuePair>();
parameters.add(p1);
parameters.add(p2);
HttpEntity httpParameterEntity=new UrlEncodedFormEntity(parameters);
//生成HttpPost对象
HttpPost httpPost=new HttpPost("http://192.168.1.92/request.php");
//设置httpPost对象的Entity来传入参数
httpPost.setEntity(httpParameterEntity);
HttpResponse httpResponse=httpClient.execute(httpPost);
//下面就和GET方法一样了
HttpEntity httpEntity=httpResponse.getEntity();
//从http实体中取出想要的信息
InputStream inputStream=httpEntity.getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
String res="";
String line="";
while((line=br.getLine())!=null){
res+=line;
}
Log.i("The Result from Server",res);
Socket网络请求
Socket是通信的基石,包括TCP/UDP
而HTTP是TCP协议的一种应用
一般情况下,对于实时性要求不高使用HTTP协议,而像网络游戏,股票等实时性要求较高需要使用Socket
Socket可以基于TCP协议也可以基于UDP协议,不过一般使用的是TCP协议的Socket
比如现在模拟一个从客户端上传文件,在服务器端进行存储的过程
//客户端代码
Socket socket=new Socket("192.168.1.92",4567); //服务器的URL,端口号为4567
//从一个文件获得流
InputStream is=new FileInputStream("d:/a.txt");
//获得客户端socket请求的流
OutputStream os=socket.getOutputStream();
//把文件流输入socket的输出流
byte[] buffer=new byte[4*1024]; int temp=0;
while((temp=is.read(buffer))!=-1) //每次从FileInputStream中读入
os.write(buffer,0,temp); //再从缓冲池中写入OutputStream
在服务器端
//生成一个Socket服务器端对象
ServerSocket serverSocket=new ServerSocket(4567);
//调用服务器端serverSocket来接受客户端发送的请求
Socket socket=serverSocket.accept();
//
InputStream is=socket.getInputStream();