第九章 Android 网络技术

1.WebView的用法

    xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.wangyamin.webviewtest.MainActivity">

   <LinearLayout
       android:layout_height="match_parent"
       android:layout_width="match_parent"
       android:orientation="horizontal"
       android:layout_weight="1"
       >
       <Button
           android:id="@+id/movie"
           android:layout_width="0dp"
           android:layout_weight="1"
           android:textSize="30dp"
           android:layout_height="match_parent"
           android:text="电影"/>
       <Button
           android:id="@+id/tv"
           android:layout_width="0dp"
           android:layout_weight="1"
           android:textSize="30dp"
           android:layout_height="match_parent"
           android:text="电视剧"/>
   </LinearLayout>
    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_weight="1"
        >
        <Button
            android:id="@+id/music"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:textSize="30dp"
            android:layout_height="match_parent"
            android:text="音乐"/>
        <Button
            android:id="@+id/variety"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:textSize="30dp"
            android:layout_height="match_parent"
            android:text="综艺"/>
    </LinearLayout>

</LinearLayout>
MainActivity中的代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private  String data = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      /*  WebView view = (WebView)findViewById( R.id.web_view);
        view.getSettings().setJavaScriptEnabled( true);
        view.setWebViewClient( new WebViewClient() );
        view.loadUrl("http://www.baidu.com");*/
      //四个按钮
        Button movie = (Button)findViewById(R.id.movie);
        movie.setOnClickListener(this);

        Button tv = (Button)findViewById(R.id.tv);
        tv.setOnClickListener(this );

        Button music = (Button)findViewById(R.id.music);
        music.setOnClickListener(this);

        Button variety = (Button)findViewById(R.id.variety);
        variety.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch( v.getId() ){
            case R.id.movie:
                 data = "http://www.9rsm.com/type/1.html";
                break;
            case R.id.tv:
                 data = "http://www.9rsm.com/type/2.html";
                break;
            case R.id.music:
                 data = "http://www.9rsm.com/type/6.html";
                break;
            case R.id.variety:
                data = "http://www.9rsm.com/type/4.html";
                break;
            default:
                break;

        }
        MovieActivity.actionStart( MainActivity.this, data );
    }
}
public class MovieActivity extends AppCompatActivity {

    private String  uri = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie);
        Intent intent = getIntent();
        uri = intent.getStringExtra("uri");
        WebView view = (WebView)findViewById( R.id.web_view);
        view.getSettings().setJavaScriptEnabled( true);
        view.setWebViewClient( new WebViewClient() );
        view.loadUrl(uri);
    }
    public  static void actionStart(Context context, String data1){
        Intent intent = new Intent( context, MovieActivity.class);
        intent.putExtra("uri", data1 );
        context.startActivity( intent);
    }
}
注意这里访问了网络要在AndroidManifest.xml中声明权限
<uses-permission android:name="android.permission.INTERNET" />

二, 使用Http协议访问网络

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context="com.example.wangyamin.networktest.MainActivity">

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>
ScrollVIew  可以以滚动屏幕的方式显示屏幕外的内容
public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    private static final String TAG = "gettcp";
    TextView responseText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button)findViewById( R.id.send_request) ;
        responseText = (TextView)findViewById( R.id.response_text );
        sendRequest.setOnClickListener( this);
       // responseText.setText( "hello");
    }

    @Override
    public void onClick(View v) {
        if( v.getId() == R.id.send_request ){
          //  sendRequestWithHttpURLConnection();
            sendRequestWithOkHttp();
        }
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://www.qq.com")
                            .build();
                    Response response = client.newCall( request ).execute();
                    String responseData = response.body().string();
                    showResponse( responseData);
                }
                catch ( Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void sendRequestWithHttpURLConnection() {
        /**
        *开启线程来请求响应
        *@author wangyamin
        *@time 2018/4/9 10:53
        */
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try{
                    URL url = new URL("http://www.baidu.com/");
                    connection = (HttpURLConnection)url.openConnection();
                    connection.setRequestMethod( "POST");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    reader = new BufferedReader(  new InputStreamReader(in) );
                    StringBuilder response = new StringBuilder();
                    String line;
                    while( (line = reader.readLine()) != null ){
                        Log.d(TAG, line);
                        response.append(line);
                    }
                    showResponse( response.toString() );
                }catch ( Exception e ){
                    e.printStackTrace();
                }finally {
                    if( reader != null ){
                        try{
                            reader.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                    if (connection != null){
                        connection.disconnect();
                    }

                }
            }
        }).start();
    }


    private void showResponse(final  String response) {
        //子线程借助runOnUiThread来更改界面
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText( response);
            }
        });
    }
}

三,使用okHttp






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值