Android开发之网络通信(HttpURLConnection,HttpClient,HttpGet,HttpPost)

public class StreamTool {
	/**
	 * 把一个inputstream里面的内容转化成一个byte[] 
	 */
	
	public static byte[] getBytes(InputStream is) throws Exception{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while((len = is.read(buffer))!=-1){
			bos.write(buffer, 0, len);
		}
		is.close();
		bos.flush();
		byte[] result = bos.toByteArray();
		System.out.println(new String(result));
		return  result;
	}
}

/**
	 * 通过get请求提交数据到服务器
	 * 
	 * @param path
	 *            服务器servlet的地址
	 * @param name
	 *            用户名
	 * @param password
	 *            密码
	 * @return 服务器返回回来的string数据
	 */
	public static String sendDataByGet(String path, String name, String password)
			throws Exception {
		String param1 = URLEncoder.encode(name);
		String param2 = URLEncoder.encode(password);
		URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		conn.setRequestMethod("GET");
		conn.setReadTimeout(5000);
		// 获取服务器返回的流信息
		InputStream is = conn.getInputStream();
		byte[] result = StreamTool.getBytes(is);

		return new String(result);
	}

	// get post
	// get 一次提交的数据数据量比较小 4K 内部其实通过组拼url的方式
	// post 可以提交比较大的数据 form表单的形式 流的方式写到服务器
	/**
	 * 采用post的方式 提交数据到服务器
	 * 
	 * @param path
	 *            服务器servlet的地址
	 * @param name
	 *            用户名
	 * @param password
	 *            密码
	 * @return 服务器返回的数据信息
	 * @throws Exception
	 */
	public static String sendDataByPost(String path, String name,
			String password) throws Exception {
		String param1 = URLEncoder.encode(name);
		String param2 = URLEncoder.encode(password);
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		String data = "name=" + param1 + "&password=" + param2;

		conn.setRequestMethod("POST");
		conn.setConnectTimeout(5000);
		// 设置 http协议可以向服务器写数据
		conn.setDoOutput(true);
		// 设置http协议的消息头
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", data.length() + "");
		// 把我们准备好的data数据写给服务器
		OutputStream os = conn.getOutputStream();
		os.write(data.getBytes());
		// httpurlconnection 底层实现 outputstream 是一个缓冲输出流
		// 只要我们获取任何一个服务器返回的信息 , 数据就会被提交给服务器 , 得到服务器返回的流信息
		int code = conn.getResponseCode();
		if (code == 200) {
			InputStream is = conn.getInputStream();
			byte[] result = StreamTool.getBytes(is);
			return new String(result);
		} else {
			throw new IllegalStateException("服务器状态异常");
		}
	}
	
	
	/**
	 * httpclient 浏览器的简单包装 
	 * new HttpClient 就相当于得到了一个浏览器 
	 */
	public static String sendDataByHttpClientGet (String path , String name,String password) throws Exception{
		
		//1. 获取到一个浏览器的实例 
		HttpClient client = new DefaultHttpClient();
		//2. 准备请求的地址 
		String param1 = URLEncoder.encode(name);
		String param2 = URLEncoder.encode(password);
		HttpGet httpGet = new HttpGet(path + "?name=" + param1 + "&password=" + param2);
		
		//3. 敲回车 发请求 
		HttpResponse  ressponse = client.execute(httpGet);
		int code = ressponse.getStatusLine().getStatusCode();
		if(code == 200){
			InputStream is  =ressponse.getEntity().getContent();
			byte[] result = StreamTool.getBytes(is);
			return new String(result);
		}
		else{
			throw new IllegalStateException("服务器状态异常");
		}
	}
	
	public static String sendDataByHttpClientPost(String path , String name,String password) throws Exception{
		
		//1. 获取到一个浏览器的实例 
		HttpClient client = new DefaultHttpClient();
		//2. 准备要请求的 数据类型 
		HttpPost httppost = new HttpPost(path);
		// 键值对 
		List< NameValuePair> parameters = new ArrayList
   
   
    
    ();
		
		parameters.add(new BasicNameValuePair("name", name));
		parameters.add(new BasicNameValuePair("password", password));
		
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
		
		
		//3.设置post请求的数据实体 
		httppost.setEntity(entity);
		
		//4. 发送数据给服务器
		HttpResponse  ressponse = client.execute(httppost);
		int code = ressponse.getStatusLine().getStatusCode();
		if(code == 200){
			InputStream is  =ressponse.getEntity().getContent();
			byte[] result = StreamTool.getBytes(is);
			return new String(result);
		}
		else{
			throw new IllegalStateException("服务器状态异常");
		}
	}

   
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值