Android中的HttpURLConnection网络请求方式

   

 post请求
String path="http://www.baidu.com";
    	String param="hehehe";
    	
		//新建一个URL对象
		try {
			URL url = new URL(path);
			// 打开一个HttpURLConnection连接  
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//设置请求方式请求post
			conn.setRequestMethod("POST");
			 // Post请求必须设置允许输出  
			conn.setDoOutput(true);
			// Post请求不能使用缓存  
			conn.setUseCaches(false);  
			// 配置请求Content-Type  Content-Length
			conn.addRequestProperty("Content-Length", param.length()+"");
			conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			OutputStream out = conn.getOutputStream();
			out.write(param.getBytes());
			// 开始连接  
			conn.connect();
			int code = conn.getResponseCode();
			// 判断请求是否成功  
			if(code==200){
				InputStream in= conn.getInputStream();
				//把字节流转化成字符流  InputStreamReader 
				 InputStreamReader isr=new InputStreamReader(in);
				//把字符流转换成缓冲字符流
				 BufferedReader br=new BufferedReader(isr);
				 //	创建一个StringBuffer
				StringBuffer sb=new StringBuffer();
				String str="";
				 while((str=br.readLine())!=null){
					 sb.append(str);
				 }
				
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

get请求
<pre name="code" class="java">	//网址
		String path="http://www.baidu.com";

		try {
			//新建一个URL对象
			URL url = new URL(path);
			// 打开一个HttpURLConnection连接  
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//设置请求方式get请求
			conn.setRequestMethod("GET");
			 // 设置连接超时时间  
			conn.setConnectTimeout(5000);
			// //再设置超时时间
			conn.setReadTimeout(5000);
			 // 开始连接  
			conn.connect();
			 // 判断请求是否成功     成功码为200
			if(200==conn.getResponseCode()){
				InputStream inputStream = conn.getInputStream();
				//把字节流转化成字符流  InputStreamReader 
				 InputStreamReader isr=new InputStreamReader(inputStream);
				//把字符流转换成缓冲字符流
				 BufferedReader br=new BufferedReader(isr);
				 //	创建一个StringBuffer
				StringBuffer sb=new StringBuffer();
				String str="";
				 while((str=br.readLine())!=null){
					 sb.append(str);
				 }
		
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值