1)基于HTTP协议
HttpURLConnection:
// Get方式请求
public static void requestByGet() throws Exception {
String path = “https://reg.163.com/logins.jsp?id=helloworld&pwd=android“;
// 新建一个URL对象
URL url = new URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
// 开始连接
urlConn.connect();
// 判断请求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
// 获取返回的数据
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_GET, “Get方式请求成功,返回数据如下:”);
Log.i(TAG_GET, new String(data, “UTF-8”));
} else {
Log.i(TAG_GET, “Get方式请求失败”);
}
// 关闭连接
urlConn.disconnect();}

// Post方式请求
public static void requestByPost() throws Throwable {
String path = “https://reg.163.com/logins.jsp“;
// 请求的参数转换为byte数组
String params = “id=” + URLEncoder.encode(“helloworld”, “UTF-8”)
+ “&pwd=” + URLEncoder.encode(“android”, “UTF-8”);
byte[] postData = params.getBytes();
// 新建一个URL对象
URL url = new URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
// Post请求必须设置允许输出
urlConn.setDoOutput(true);
// Post请求不能使用缓存
urlConn.setUseCaches(false);
// 设置为Post请求
urlConn.setRequestMethod(“POST”);
urlConn.setInstanceFollowRedirects(true);
// 配置请求Content-Type
urlConn.setRequestProperty(“Content-Type”,
“application/x-www-form-urlencode”);
// 开始连接
urlConn.connect();
// 发送请求参数
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
dos.write(postData);
dos.flush();
dos.close();
// 判断请求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
// 获取返回的数据
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_POST, “Post请求方式成功,返回数据如下:”);
Log.i(TAG_POST, new String(data, “UTF-8”));
} else {
Log.i(TAG_POST, “Post方式请求失败”);
}}

HttpClient
Get方式
1, 创建HttpClient对象

2,创建HttpGet对象,指定请求地址(带参数)

3,使用HttpClient的execute(),方法执行HttpGet请求,得到HttpResponse对象

4,调用HttpResponse的getStatusLine().getStatusCode()方法得到响应码

5,调用的HttpResponse的getEntity().getContent()得到输入流,获取服务端写回的数据
//先将参数放入List,再对参数进行URL编码
List params = new LinkedList();
params.add(new BasicNameValuePair(“param1”, “中国”));
params.add(new BasicNameValuePair(“param2”, “value2”));

//对参数编码
String param = URLEncodedUtils.format(params, “UTF-8”);

//baseUrl
String baseUrl = “http://ubs.free4lab.com/php/method.php“;

//将URL与参数拼接
HttpGet getMethod = new HttpGet(baseUrl + “?” + param);

HttpClient httpClient = new DefaultHttpClient();

try {
HttpResponse response = httpClient.execute(getMethod); //发起GET请求

Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//获取服务器响应内容

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Post方式
1,创建HttpClient对象
2,创建HttpPost对象,指定请求地址
3,创建List,用来装载参数
4,调用HttpPost对象的setEntity()方法,装入一个UrlEncodedFormEntity对象,携带之前封装好的参数
5,使用HttpClient的execute()方法执行HttpPost请求,得到HttpResponse对象
6, 调用HttpResponse的getStatusLine().getStatusCode()方法得到响应码
7, 调用的HttpResponse的getEntity().getContent()得到输入流,获取服务端写回的数据

//和GET方式一样,先将参数放入List
params = new LinkedList();
params.add(new BasicNameValuePair(“param1”, “Post方法”));
params.add(new BasicNameValuePair(“param2”, “第二个参数”));

try {
HttpPost postMethod = new HttpPost(baseUrl);
postMethod.setEntity(new UrlEncodedFormEntity(params, “utf-8”)); //将参数填入POST Entity中

HttpResponse response = httpClient.execute(postMethod); //执行POST方法Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //获取响应内容

} 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();
}

2)基于socket
基于TCP协议的Socket
服务器端首先声明一个ServerSocket对象并且指定端口号,然后调用Serversocket的accept()方法接收客户端的数据。accept()方法在没有数据进行接收的处于堵塞状态。(Socketsocket=serversocket.accept()),一旦接收到数据,通过inputstream读取接收的数据。
客户端创建一个Socket对象,指定服务器端的ip地址和端口号(Socketsocket=newSocket(“172.168.10.108”,8080);),通过inputstream读取数据,获取服务器发出的数据(OutputStreamoutputstream=socket.getOutputStream()),最后将要发送的数据写入到outputstream即可进行TCP协议的socket数据传输。

基于UDP协议的数据传输
服务器端首先创建一个DatagramSocket对象,并且指点监听的端口。接下来创建一个空的DatagramSocket对象用于接收数据(bytedata[]=newbyte[1024;]DatagramSocketpacket=newDatagramSocket(data,data.length)),使用DatagramSocket的receive方法接收客户端发送的数据,receive()与serversocket的accepet()类似,在没有数据进行接收的处于堵塞状态。
客户端也创建个DatagramSocket对象,并且指点监听的端口。接下来创建一个InetAddress对象,这个对象类似与一个网络的发送地址(InetAddressserveraddress=InetAddress.getByName(”172.168.1.120”)).定义要发送的一个字符串,创建一个DatagramPacket对象,并制定要讲这个数据报包发送到网络的那个地址以及端口号,最后使用DatagramSocket的对象的send()发送数据。

但是相对来说使用Http方式请求的较多,因此可以主要使用Http的方式。

参考网址:
1、http://www.cnblogs.com/hoji-real/articles/2362985.html
2、http://www.2cto.com/kf/201501/368943.html
3、http://blog.csdn.net/maoxiao1229/article/details/22886337

更多相关文章

  1. Android之使用Pull解析Xml数据
  2. android SQLite数据库2
  3. Android 创建SQLite数据库(一)
  4. Android利用wireshark抓取网络数据包
  5. Android 中数据库查询方法 query() 中的 selectionArgs 的用法
  6. Android 列表数据写入到本地Excel文件(包括图片)
  7. android中的sqlit3数据库进行手机应用软件开发(自写的一个财务管
  8. Android访问WCF服务(使用json实现参数传递)
  9. 6.1、Android中从Internet获取数据

随机推荐

  1. android 颜色资源
  2. Android:获取状态栏高度
  3. Android(安卓)Framework---themes.xml
  4. android setPersistent
  5. android截屏
  6. android 调用摄像头
  7. adt或eclipse中Android工程如何互相引用
  8. Android(安卓)SeekBar(拖动条)
  9. Android(安卓)WebView文件上传(关键代码)
  10. Android学习札记37:onSaveInstanceState (