Http协议访问网络

来源:互联网 发布:relieff算法 matlab 编辑:程序博客网 时间:2024/06/08 20:42

WebView控件以及OkHttp类的使用:

代码如下:

MainActivity.class:

import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.TextView;import java.io.IOException;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;public class MainActivity extends AppCompatActivity {    private TextView textView;    private WebView webView;    @Override    protected void onCreate(Bundle saveInstance) {        setContentView(R.layout.activity_main);        super.onCreate(saveInstance);        //在WebView控件中显示百度首页        webView=(WebView)findViewById(R.id.webView);        webView.getSettings().setJavaScriptEnabled(true);   //设置支持javaScript脚本        webView.setWebViewClient(new WebViewClient());      //使打开一个新网页是以WebView控件打开而不是用浏览器        webView.loadUrl("http://www.baidu.com");        //设置地址        //在TextView控件中获取百度首页源代码        new Thread(new Runnable(){            @Override            public void run(){                try{                    OkHttpClient client=new OkHttpClient(); //该类需要在app/build.gradle中添加指定内容                    Request request=new Request.Builder()                            .url("http://www.baidu.com")                            .build();                    Response response=client.newCall(request).execute();                    String responseData=response.body().string();                    showData(responseData);                }catch(IOException e){                    e.printStackTrace();                }            }        }).start();    }    private void showData(final String str){        //在子线程中不能操作UI,所以要回到主线程中操作        runOnUiThread(new Runnable(){            @Override            public void run(){                Log.i("INFORMATION",str);                textView=(TextView)findViewById(R.id.textView);                textView.setText(str);            }        });    }}
在build.gradle需要添加的内容如下:

dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {        exclude group: 'com.android.support', module: 'support-annotations'    })    compile 'com.android.support:appcompat-v7:25.3.1'    compile 'com.android.support.constraint:constraint-layout:1.0.2'    testCompile 'junit:junit:4.12'    compile 'com.squareup.okhttp3:okhttp:3.4.1'}


原创粉丝点击