一、WebView

这个View就是一个浏览器,用于展示网页的。

布局文件:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView> </LinearLayout>

java代码:

 public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); WebView webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.baidu.com");
}
}

webView.getSettings().setJavaScriptEnabled(true)这个方法传入true,让WebView支持JavaScript脚本

webView.setWebViewClient(new WebViewClient()),实现了当需要从一个网页跳到另一个网页的时候,希望也在这个WebView中显示

AndroidManifest文件权限添加:

<uses-permission android:name="android.permission.INTERNET"/>

效果:

二、HTTP协议访问数据

  工作原理:客户端向服务器发出一条HTTP请求,服务器收到请求后会返回一些数据给客户端,然后客户端再对数据进行解析和处理。

  1、使用HttpURLConnection

    基本用法:

      * 首先获取到HttpURLConnection的实例

  URL url = new URL("https://www.baidu.com");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();

      *设置HTTP请求是希望从服务器获取数据(GET),还是希望提交数服务器(POST) 

  connection.setRequestMethod("GET");

      *设置连接超时的时间,读取超时的时间:

  connection.setConnectTimeout(8000);
  connection.setReadTimeout(8000);

      *调用getInputStream()方法获取到服务器的输入流:

  InputStream in = connection.getInputStream();

      *最后调用disconnect()把这个HTTP连接关掉:

  connection.disconnect();

实例应用程序:

  布局代码:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送" /> <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>

  java代码:

 public class MainActivity extends AppCompatActivity{

     TextView responseText;//用于展示从服务器获取到的文本的控件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //控件注册
final Button sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text); //按钮相应
sendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendRequestWithHttpURLConnection();
}
});
} private void sendRequestWithHttpURLConnection(){ //开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL("https://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
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){
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(new Runnable() {
@Override
public void run() {
//UI操作
responseText.setText(response);
}
});
}
}

效果:

  2、使用OkHttp

    这是一个用来代替HttpURLConnection的开源库

    基本用法:

      *添加OkHttp库的依赖

compile 'com.squareup.okhttp3:okhttp:3.9.0'

      *创建一个OkHttpClient的实例

OkHttpClient client = new OkHttpClient();

      *创建一个Request实例,并连缀其他方法丰富这个对象

Request request = new Request.Builder()
  .url("http://www.baidu.com")
  .build();

      *获取返回的数据

  Response response = client.newCall(request).execute();

修改上面的程序:

 public class MainActivity extends AppCompatActivity{

     TextView responseText;//用于展示从服务器获取到的文本的控件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //控件注册
final Button sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text); //按钮相应
sendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendRequestWithHttpURLConnection();
}
});
} private void sendRequestWithHttpURLConnection(){ //开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
try{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
} private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
//UI操作
responseText.setText(response);
}
});
}
}

效果同样。。

最新文章

  1. WINDOWS系统下MYSQL安装过程中的注意事项
  2. 认识和使用NSOperation
  3. Java基础---AWT
  4. 【Mail】telnet收发邮件过程
  5. 安装及破解IntelliJ IDEA15
  6. oracle添加日志表
  7. C++重要知识点小结---3
  8. RichTextBox 右键显示 ContextMenuTrip 分类: C# 2014-10-16 10:43 337人阅读 评论(0) 收藏
  9. angularJS function
  10. eChart学习笔记
  11. spring 的单例模式
  12. ubuntu连接android设备(附最简单方法)
  13. ORACLE中INSERT插入多条数据
  14. tyvj/joyoi 1374 火车进出栈问题(水水版)
  15. Solidworks设计电路外形导入AltiumDesigner
  16. centos7 安装curl-7.51.0
  17. Java基础学习-HelloWorld案例的编写和运行
  18. 单字段去重 distinct 返回其他多个字段
  19. [转]WordPress主题开发:主题初始化
  20. C# 枚举 小总结

热门文章

  1. 小代介绍Spring Boot
  2. Modbus 指令
  3. 2019 Java 全栈工程师进阶路线图,一定要收藏
  4. SQL Server 触发器和事务
  5. Bzoj 2525 [Poi2011]Dynamite
  6. cogs426血帆海盗(网络流打法)
  7. I/O:ByteBuffer
  8. [原创]Floodlight安装
  9. Redis原子性写入HASH结构数据并设置过期时间
  10. P4071 [SDOI2016]排列计数 题解