package com.example.wang.testapp3;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class TestActivity3 extends AppCompatActivity {
EditText et_2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test3);
et_2=(EditText)findViewById(R.id.et_2);
}
//JDK的Get方式
public void bt1_OnClick(View v)
{
//1.進度對話框
final ProgressDialog progressDialog = ProgressDialog.show(this, null, "正在加載,請稍候...");
//2.開啓子線程,訪問網絡
new Thread(){
public void run()
{
try {
// 1 - URL
URL url = new URL("http://www.baidu.com");
// 2- URL獲取鏈接
HttpURLConnection huc = (HttpURLConnection)url.openConnection();
//請求方式
huc.setRequestMethod("GET");
//設置超時
huc.setConnectTimeout(3000);
huc.setReadTimeout(3000);
//鏈接併發送請求
huc.connect();
//接收:
// 判斷返回狀態碼 200
int code = huc.getResponseCode();
if (code == 200) {
// 接收數據
// 輸入流:
InputStream is = huc.getInputStream();
//讀取流
//1-byte數組
byte[] b = new byte[1024];
//2-讀到數組的長度
int i = 0;
//3-數據
final StringBuilder sb1 = new StringBuilder();
while((i = is.read(b)) > 0)
{
sb1.append(new String(b, 0, i));
}
// 釋放資源
is.close();
huc.disconnect();
// 經過主線程顯示信息和關閉對話框
runOnUiThread(new Runnable() {
@Override
public void run() {
et_2.setText(sb1);
progressDialog.dismiss();
Log.e("TAG", "鏈接錯誤11");
}
}
);
}
else
{
Toast.makeText(TestActivity3.this, "鏈接錯誤,返回的狀態碼 = " + code, Toast.LENGTH_SHORT).show();
Log.e("TAG","鏈接錯誤");
}
}
catch (Exception e)
{
e.printStackTrace();
progressDialog.dismiss();
}
}
}.start();
}
}