//MainActivity
public class MainActivity extends AppCompatActivity {
private TextView showText;
private Button sure;
ExecutorService pool;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
showText.setText(msg.obj.toString());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pool= Executors.newSingleThreadExecutor();
initView();
}
private void initView() {
showText = (TextView) findViewById(R.id.showText);
sure = (Button) findViewById(R.id.sure);
}
/**
* onClick点击事件
* @param v
*/
public void sure(View v) {
if (v.getId() == R.id.sure) {
final HttpUtil httpUtil = new HttpUtil(new NetWorkCallbackInterface() {
@Override
public void showCallback(String result) {
Message msg = new Message();
msg.what = 1;
msg.obj = result;
handler.sendMessage(msg);
}
});
pool.execute(new Thread(new Runnable() {
@Override
public void run() {
httpUtil.getRespText();
}
}));
}
}
}
//请求网络数据工具类
public class HttpUtil {
private NetWorkCallbackInterface netWorkCallback;
private final int CONNECT_TIME_OUT = 5 * 1000;
private final int READ_TIME_OUT = 10 * 1000;
public HttpUtil(NetWorkCallbackInterface callback){
this.netWorkCallback = callback;
}
public void getRespText(){
netWorkCallback.showCallback(doGet("http://wwww.baidu.com", null));
}
private URL url = null;
private HttpURLConnection uRLConnection_GET;
// 向服务器发送get请求
private String doGet(String urlAddress, String params) {
if (params == null)
params = "";
try {
url = new URL(urlAddress + params);
uRLConnection_GET = (HttpURLConnection) url.openConnection();
// 接连超时
uRLConnection_GET.setConnectTimeout(CONNECT_TIME_OUT);
// 响应超时
uRLConnection_GET.setReadTimeout(READ_TIME_OUT);
InputStream is = uRLConnection_GET.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String response = "";
String readLine = null;
while ((readLine = br.readLine()) != null) {
response = response + readLine;
}
is.close();
br.close();
uRLConnection_GET.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
//返回请求数据的接口
public interface NetWorkCallbackInterface{
void showCallback(String result);
}
注释:部分内容摘自别的大神所作,谢谢。
注:如有问题可以回复,看到第一时间分析解决,码农不易,感觉对您有用,帮助到您,可否打赏一杯可乐,在此谢过诸位,愿诸君终成大神,前程似锦~~~