Android Network request get method, android request get
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 ){
/* Method 1 * // * Thread thread = new Thread (new Runnable () {@ Override public void run () {HttpUrlConnectionGet () ;}}); thread. start ();*/
/* Method 2 */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 (). setdefatextextencodingname ("UTF-8"); webView. getSettings (). setJavaScriptEnabled (true); webView. loadDataWithBaseURL (null, s, "text/html", "UTF-8", null );}}};}