关闭

HttpUrlConnection的用法

86人阅读 评论(0) 收藏 举报
<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>

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1991次
    • 积分:246
    • 等级:
    • 排名:千里之外
    • 原创:24篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条