通过URL和HttpURLConnection发送网络协议获取内容,在通过InputStream和BufferedReader读取每一行内容,网络请求不能在主线程中发送,所以需要开启一个子线程来发送网络命令。然而在子线程中也不能访问UI内容,所以又需要回到主线程中显示内容。
@Override
protected void onCreate(Bundle savedInstanceState) {
Button button13 = (Button)findViewById(R.id.button13);
button13.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL("http://www.chicai.group");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.connect();
int responseCode = connection.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_OK) return;
InputStream in = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
String line;
StringBuilder response = new StringBuilder();
while((line = reader.readLine()) != null )
{
response.append(line);
}
ShowResponse(response.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if(reader != null)
{
try{
reader.close();
}catch (IOException e)
{
e.printStackTrace();
}
}
if(connection != null)
connection.disconnect();
}
}
}).start();
}
});
}
private void ShowResponse(final String str)
{
runOnUiThread(new Runnable() {//异步消息处理机制的接口封装
@Override
public void run() {
Toast.makeText(Main2Activity.this,str,Toast.LENGTH_LONG).show();
}
});
}