package com.example.phonehttp;
import android.os.Bundle;
import android.os.Handler;import android.app.Activity;import android.widget.ScrollView;import android.widget.TextView;public class MainActivity extends Activity {
Handler handler = new Handler();
ScrollView scroll; TextView tv;@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);scroll = (ScrollView) findViewById(R.id.scroll);
tv = (TextView) findViewById(R.id.tv);String url = "https://home.cnblogs.com/news/";
HttpThread httpThread = new HttpThread(url, scroll, tv, handler);
httpThread.start(); }}
package com.example.phonehttp;
import java.io.BufferedReader;
import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.os.Handler;
import android.view.View;import android.widget.ScrollView;import android.widget.TextView;public class HttpThread extends Thread {
String str;String url;
ScrollView scroll; TextView tv; Handler handler; public HttpThread(String url,ScrollView scroll,TextView tv,Handler handler) { // TODO Auto-generated constructor stub this.url = url; this.scroll = scroll; this.tv = tv; this.handler = handler; }@Override
public void run() { // TODO Auto-generated method stub try { URL Httpurl = new URL(url); HttpURLConnection conn = (HttpURLConnection) Httpurl .openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() != 200) { throw new RuntimeException("请求url失败"); } BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); while ((str = bufferedReader.readLine()) != null) { sb.append(str); } str = sb.toString(); handler.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub scroll.setVisibility(View.VISIBLE); tv.setText(str); } }); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" ><TextView
android:id="@+id/txtMenu" android:layout_width="match_parent" android:layout_height="48dp" android:background="#E0FFFF" android:clickable="true" android:gravity="center" android:text="@string/hello_world" android:textSize="20sp" /> <ScrollView android:id="@+id/scroll" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </ScrollView></LinearLayout>