HttpUrlConnection的用法

<span style="font-size:18px;">public class MainActivity extends Activity {

	private TextView textView;

	
	Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			
			String data = (String) msg.obj;
			textView.setText(data);
		};
		
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		textView = (TextView) findViewById(R.id.textView);
		
		
		new Thread() {

			public void run() {
				getData();
			};

		}.start();
		
	}

	/**
	 * 联网请求数据
	 */
	private void getData() {
		try {
			
			//得到URL对象,并设置访问地址
			URL url=new URL("http://www.baidu.com/");
			//得到HttpURLConnection对象
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();	
			//设置连接超时
			httpURLConnection.setConnectTimeout(5000);
			//设置请求方式 get/post
			httpURLConnection.setRequestMethod("POST");
			//读取超时
			httpURLConnection.setReadTimeout(5000);
			
			//正式联网
			httpURLConnection.connect();
			//获得状态码
			int code =httpURLConnection.getResponseCode();
			
			if(code==200){
				
				System.out.println("联网请求成功");
				
				//获取包含数据的输入流
				InputStream inputStream = httpURLConnection.getInputStream();
				
				BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
				//记录每一行读取的数据
				String data;
				//拼接字符串
				StringBuffer stringBuffer=new StringBuffer();
				while ((data=bufferedReader.readLine())!=null) {
					stringBuffer.append(data);
					
				}
				
				
			/*	System.out.println(stringBuffer.toString());
				
				textView.setText(stringBuffer.toString());*/
				
				Message msg = Message.obtain();
				msg.obj=stringBuffer.toString();
				handler.sendMessage(msg);
				
			}else{
				
				System.out.println("联网失败");
				
			}
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}



}</span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值