HttpURLConnection发送网络请求的用法

public class MainActivity extends Activity implements OnClickListener{
	private Button sendRequest;
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
		}
		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		sendRequest=(Button) findViewById(R.id.send_request);
		sendRequest.setOnClickListener(this);
		
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId())
		{
		case R.id.send_request:
			sendRequestWithHttpURLConnection();
			break;
			default:
				break;
		}
		
	}
	private void sendRequestWithHttpURLConnection()
	{
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				HttpURLConnection connection=null;
				try{
					URL url=new URL("http://www.baidu.com");
					connection=(HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8000);
					connection.setReadTimeout(8000);
					InputStream in=connection.getInputStream();
					BufferedReader reader=new BufferedReader(new InputStreamReader(in));
					StringBuilder response=new StringBuilder();
					String line;
					while((line=reader.readLine())!=null)
					{
						response.append(line);
					}
					Message msg=new Message();
					msg.what=1;
					msg.obj=line;
					handler.sendMessage(msg);
				}catch(Exception e)
				{
					e.printStackTrace();
				}
				finally{
					if(connection!=null)
					{
						connection.disconnect();
					}
				}
				
			}
		}).start();
	}

	}

阅读更多
个人分类: Android
上一篇Context.bindService()详解
下一篇Tomcat和Apache部署XML,JSON文件
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭