Android基础知识——使用网络技术
发布日期:2021-05-19 15:52:51 浏览次数:12 分类:精选文章

本文共 14344 字,大约阅读时间需要 47 分钟。

WebView的用法

在Android开发中,有时候需要在应用程序中嵌入一个浏览器来展示网页,而不允许用户直接打开系统浏览器。WebView控件正是用来实现这一需求的。

使用步骤

  • 在布局文件中添加WebView控件

    在Android项目的布局文件中添加WebView控件,通常使用XML结构如下:

  • 在活动中获取WebView实例

    在Activity类中找到WebView控件,并设置其支持JavaScript:

    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支持JavaScript

    WebView默认不支持JavaScript,可以通过设置setJavaScriptEnabled(true)来启用:

    webView.getSettings().setJavaScriptEnabled(true);
  • 让网页在WebView中打开

    使用loadUrl方法加载网页:

    webView.loadUrl("https://www.baidu.com");
  • 传入网址

    需要注意的是,loadUrl方法会自动处理HTTP和HTTPS URL。

  • 示例

    完整的实现代码如下:

    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("https://www.baidu.com");      }  }

    注意事项

    • 网络权限:如果需要访问网络,需要在AndroidManifest.xml中添加 INTERNET权限:

    使用HTTP协议访问网络

    HTTP协议是客户端和服务器之间进行通信的标准协议。Android上发送HTTP请求有两种常用方式:HttpURLConnectionOkHttp

    使用HttpURLConnection

    示例代码

    public class MainActivity extends AppCompatActivity {      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          final Button button = (Button) findViewById(R.id.button);          final TextView textView = (TextView) findViewById(R.id.text);          button.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View view) {                  new Thread(new Runnable() {                      @Override                      public void run() {                          try {                              URL url = new URL("https://www.baidu.com");                              HttpURLConnection connection = (HttpURLConnection) url.openConnection();                              connection.setRequestMethod("GET");                              connection.setReadTimeout(8000);                              connection.setConnectTimeout(8000);                              InputStream in = connection.getInputStream();                              BufferedReader reader = new BufferedReader(new InputStreamReader(in));                              final StringBuilder content = new StringBuilder();                              String line;                              while ((line = reader.readLine()) != null) {                                  content.append(line);                              }                              MainActivity.this.runOnUiThread(new Runnable() {                                  @Override                                  public void run() {                                      textView.setText(content.toString());                                  }                              });                          } catch (Exception e) {                              e.printStackTrace();                          } finally {                              if (reader != null) {                                  try {                                      reader.close();                                  } catch (IOException e) {                                      e.printStackTrace();                                  }                              }                              if (connection != null) {                                  connection.disconnect();                              }                          }                      }                  }).start();              }          });      }  }

    POST请求示例

    如果需要提交数据,可以将HTTP方法设置为POST,并添加请求体:

    connection.setRequestMethod("POST");  DataOutputStream out = new DataOutputStream(connection.getOutputStream());  out.writeBytes("username=admin&password=123456");

    使用OkHttp

    依赖声明

    在项目的build.gradle中添加OkHttp依赖:

    implementation 'com.squareup.okhttp3:okhttp:4.8.1'

    示例代码

    public class MainActivity extends AppCompatActivity {      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          final Button button = (Button) findViewById(R.id.button);          final TextView textView = (TextView) findViewById(R.id.text);          button.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View view) {                  new Thread(new Runnable() {                      @Override                      public void run() {                          try {                              OkHttpClient client = new OkHttpClient();                              Request request = new Request.Builder()                                      .url("https://www.baidu.com")                                      .build();                              Response response = client.newCall(request).execute();                              final String content = response.body().string();                              MainActivity.this.runOnUiThread(new Runnable() {                                  @Override                                  public void run() {                                      textView.setText(content);                                  }                              });                          } catch (Exception e) {                              e.printStackTrace();                          }                      }                  }).start();              }          });      }  }

    POST请求示例

    如果需要提交数据,可以通过OkHttp的post()方法:

    RequestBody requestBody = new FormBody.Builder()          .add("username", "admin")          .add("password", "123456")          .build();  Request request = new Request.Builder()          .url("https://www.baidu.com")          .post(requestBody)          .build();

    解析XML格式数据

    在网络传输中,XML是常用的数据格式。Android支持两种解析方式:Pull解析和SAX解析。

    Pull解析

    示例代码

    private void parseXMLWithPull(String xmlData) {      try {          XmlPullParserFactory factory = XmlPullParserFactory.newInstance();          XmlPullParser parser = factory.newPullParser();          parser.setInput(new StringReader(xmlData));          int eventType = parser.getEventType();          String id = "";          String name = "";          String version = "";          while (eventType != XmlPullParser.END_DOCUMENT) {              String nodeName = parser.getName();              switch (eventType) {                  case XmlPullParser.START_TAG: {                      if ("id".equals(nodeName)) {                          id = parser.nextText();                      } else if ("name".equals(nodeName)) {                          name = parser.nextText();                      } else if ("version".equals(nodeName)) {                          version = parser.nextText();                      }                      break;                  }                  case XmlPullParser.END_TAG: {                      if ("app".equals(nodeName)) {                          Log.e("MainActivity", id);                          Log.e("MainActivity", name);                          Log.e("MainActivity", version);                      }                      break;                  }                  default:                      break;              }              eventType = parser.next();          }      } catch (Exception e) {          e.printStackTrace();      }  }

    SAX解析

    自定义Handler类

    public class MyHandler extends DefaultHandler {      StringBuilder id;      StringBuilder name;      StringBuilder version;      String nodeName;      @Override      public void startDocument() throws SAXException {          super.startDocument();          id = new StringBuilder();          name = new StringBuilder();          version = new StringBuilder();      }      @Override      public void startElement(String uri, String localName, String qName, Attributes attributes)              throws SAXException {          super.startElement(uri, localName, qName, attributes);          nodeName = localName;      }      @Override      public void characters(char[] ch, int start, int length) throws SAXException {          super.characters(ch, start, length);          if ("id".equals(nodeName)) {              id.append(ch, start, length);          } else if ("name".equals(nodeName)) {              name.append(ch, start, length);          } else if ("version".equals(nodeName)) {              version.append(ch, start, length);          }      }      @Override      public void endElement(String uri, String localName, String qName) throws SAXException {          super.endElement(uri, localName, qName);          if ("app".equals(nodeName)) {              Log.e("MyHandler", id.toString().trim());              Log.e("MyHandler", name.toString().trim());              Log.e("MyHandler", version.toString().trim());          }          id.setLength(0);          name.setLength(0);          version.setLength(0);      }      @Override      public void endDocument() throws SAXException {          super.endDocument();      }  }

    使用示例

    private void parseXMLWithSAX(String xmlData) {      try {          SAXParserFactory factory = SAXParserFactory.newInstance();          XMLReader reader = factory.newSAXParser().getXMLReader();          MyHandler myHandler = new MyHandler();          reader.setDTDHandler(myHandler);          reader.parse(new InputSource(new StringReader(xmlData)));      } catch (Exception e) {          e.printStackTrace();      }  }

    解析JSON数据

    JSON格式的数据解析可以使用JSONObjectGSON库。

    使用JSONObject

    示例代码

    private void parseJSONWithJSONObject(String jsonData) {      try {          JSONArray array = new JSONArray(jsonData);          for (int i = 0; i < array.length(); i++) {              JSONObject obj = array.optJSONObject(i);              String id = obj.optString("id");              String name = obj.optString("name");              String version = obj.optString("version");              Log.e("MainActivity", id);              Log.e("MainActivity", name);              Log.e("MainActivity", version);          }      } catch (Exception e) {          e.printStackTrace();      }  }

    使用GSON

    定义数据类

    public class App {      private String id;      private String name;      private String version;      public String getId() {          return id;      }      public void setId(String id) {          this.id = id;      }      public String getName() {          return name;      }      public void setName(String name) {          this.name = name;      }      public String getVersion() {          return version;      }      public void setVersion(String version) {          this.version = version;      }  }

    使用示例

    Gson gson = new Gson();  List
    apps = gson.fromJson(jsonData, new TypeToken
    >() {}.getType()); for (App app : apps) { Log.e("MainActivity", app.getId()); Log.e("MainActivity", app.getName()); Log.e("MainActivity", app.getVersion()); }

    网络编程的最佳实践

    HttpCallbackListener接口

    public interface HttpCallbackListener {      void onFinish(String response);      void onError(Exception e);  }

    HttpUtil类

    public class HttpUtil {      public static void sendHttpRequest(String address, HttpCallbackListener listener) {          new Thread(new Runnable() {              @Override              public void run() {                  HttpURLConnection connection = null;                  BufferedReader reader = null;                  try {                      URL url = new URL(address);                      connection = (HttpURLConnection) url.openConnection();                      connection.setRequestMethod("GET");                      connection.setReadTimeout(8000);                      connection.setConnectTimeout(8000);                      InputStream in = connection.getInputStream();                      BufferedReader reader = new BufferedReader(new InputStreamReader(in));                      StringBuilder content = new StringBuilder();                      String line;                      while ((line = reader.readLine()) != null) {                          content.append(line);                      }                      if (listener != null) {                          listener.onFinish(content.toString());                      }                  } catch (Exception e) {                      if (listener != null) {                          listener.onError(e);                      }                  } finally {                      if (reader != null) {                          try {                              reader.close();                          } catch (IOException e) {                              e.printStackTrace();                          }                      }                      if (connection != null) {                          connection.disconnect();                      }                  }              }          }).start();      }  }

    MainActivity调用方法

    public void onClick(View view) {      HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {          @Override          public void onFinish(String response) {              // 处理成功响应          }          @Override          public void onError(Exception e) {              // 处理异常          }      });  }

    OkHttp最佳实践

    HttpUtil类

    public class HttpUtil {      public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {          OkHttpClient client = new OkHttpClient();          Request request = new Request.Builder()                  .url(address)                  .build();          client.newCall(request).enqueue(callback);      }  }

    MainActivity调用方法

    public void onClick(View view) {      HttpUtil.sendOkHttpRequest(address, new okhttp3.Callback() {          @Override          public void onFailure(Call call, IOException e) {              // 处理失败          }          @Override          public void onResponse(Call call, Response response) throws IOException {              // 处理成功响应              String responseData = response.body().string();          }      });  }

    通过以上方法,可以更高效地处理网络请求,并在UI线程上更新UI组件。

    上一篇:Android基础知识——探究服务
    下一篇:Android基础知识——探究内容提供器

    发表评论

    最新留言

    感谢大佬
    [***.8.128.20]2025年05月06日 04时44分44秒

    关于作者

        喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
    -- 愿君每日到此一游!

    推荐文章