package com.jredu.helloworld.activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.webkit.WebView; import android.widget.Button; import android.widget.TextView; import com.jredu.helloworld.R; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpUrlConnectionGetActivity extends AppCompatActivity { WebView webView; Button button; TextView success; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_http_url_connection_get); webView = (WebView) findViewById(R.id.baidu); success = (TextView) findViewById(R.id.success); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
/*第一种方法*/ /*Thread thread = new Thread(new Runnable() { @Override public void run() { HttpUrlConnectionGet(); } }); thread.start();*/
/*第二种方法*/ new Thread(new Runnable() { @Override public void run() { HttpUrlConnectionGet(); } }).start(); } }); } public void HttpUrlConnectionGet(){ HttpURLConnection urlConnection = null; InputStream is = null; StringBuilder sb = new StringBuilder(); try { URL url = new URL("http://apis.baidu.com/txapi/tiyu/tiyu?num=10&page=1"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(5*1000); urlConnection.setReadTimeout(5*1000); urlConnection.setRequestProperty("apikey","fc642e216cd19906f642ee930ce28174"); urlConnection.connect(); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){ is = urlConnection.getInputStream(); byte[] bytes = new byte[1024]; int i = 0; while ((i = is.read(bytes)) != -1){ sb.append(new String(bytes,0,i,"utf-8")); } is.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if (urlConnection != null){ urlConnection.disconnect(); } } Message message = handler.obtainMessage(1,sb.toString()); handler.sendMessage(message); } private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg != null && msg.what == 1){ String s = (String) msg.obj; webView.getSettings().setDefaultTextEncodingName("utf-8"); webView.getSettings().setJavaScriptEnabled(true); webView.loadDataWithBaseURL(null,s,"text/html","utf-8",null); } } }; }