关闭

HttpURLConnection发送网络请求的用法

68人阅读 评论(0) 收藏 举报
分类:
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();
	}

	}

0
0

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