使用HttpURLConnection
- 主要代码如下,布局文件就不再贴出,
- 代码逻辑就是点击按钮,使用HttpURLConnection访问百度首页,并获取百度首页的源码
- 当获取到源码的时候,通过消息处理机制,更行TextView显示的内容
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button button;
private TextView textView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
button= (Button) findViewById(R.id.button);
textView= (TextView) findViewById(R.id.textView);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
startUri();
break;
}
}
private void startUri() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url=new URL("http://www.baidu.com");
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String sb=new String();
String str=br.readLine();
while (str!=null){
sb+=str;
str=br.readLine();
}
br.close();
Message msg=new Message();
msg.obj=sb;
myHandler.sendMessage(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private Handler myHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
textView.setText(msg.obj.toString());
}
};
}