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();
}
}
HttpURLConnection发送网络请求的用法
最新推荐文章于 2023-10-09 12:08:45 发布