zoukankan      html  css  js  c++  java
  • Android学习——使用http协议访问网络

    在过去,Android上发送HTTP请求有两种方式:HttpURLConnection和HttpClient。
    不过由于HttpClient存在API数量过多,扩展困难等缺点,Android团队越来越不建议我们使用这种方式。终于在Android6.0系统中,HttpClient的功能被完全移除了,标志着此功能正式弃用。

    首先需要获取到HttpURLConnection的实例,一般只需new出一个URL对象,并传入目标的网络地址,然后调用一下openConnection()方法即可,如下所示:

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

    在得到HttpURLConnection的实例之后,我们可以设置一下HTTP请求所使用的方法,常用的方法主要有两个,GET和POST。GET表示希望从服务器那里获取数据,而POST则表示希望提交数据给服务器。写法如下:
    connection.setRequestMethod(“GET”);
    接下来就可以进行一些自由的定制了,比如设置链接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头等。这部分根据自己的实际情况进行编写,示例写法如下:

    1     connection.setConnectionTimeout(8000);
    2     connection.setReadTimeout(8000);

    之后再调用getInputStream()方法就可以获取到服务器返回的输入流了,剩下的任务就是对输入流进行读取,如下所示:

    1     InputStream in = connection.getInputStream();

    最后可以调用disconnect()方法将这个HTTP链接关闭掉,如下所示:

    1     connection.disconnect();

    下面通过例子体验HttpURLConnection的用法。新建一个NetworkTest项目,首先修改
    activity_main.xml中代码

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:orientation="vertical"
     4     android:layout_width="match_parent"
     5     android:layout_height="match_parent">
     6     <Button
     7         android:id="@+id/send_request"
     8         android:layout_width="match_parent"
     9         android:layout_height="wrap_content"
    10         android:text="Send Request"
    11         />
    12     <ScrollView
    13         android:layout_width="match_parent"
    14         android:layout_height="match_parent">
    15         <TextView
    16             android:id="@+id/response_text"
    17             android:layout_width="match_parent"
    18             android:layout_height="wrap_content" />
    19     </ScrollView>
    20 </LinearLayout>

    crollView,借助它就可以滚动的形式查看屏幕外的那部分内容。另外,布局还放置了一个Button和一个TextView,Button用于发送HTTP请求,TextView用于将服务器返回的数据显示出来。

    接着修改代码MainActivity中的代码,如下所示:

      1 package net.nyist.lenovo.networktest;
      2 
      3 
      4 import android.support.v7.app.AppCompatActivity;
      5 import android.os.Bundle;
      6 import android.util.Log;
      7 import android.view.View;
      8 import android.widget.Button;
      9 import android.widget.TextView;
     10 
     11 import java.io.BufferedReader;
     12 import java.io.IOException;
     13 import java.io.InputStream;
     14 import java.io.InputStreamReader;
     15 import java.net.HttpURLConnection;
     16 import java.net.MalformedURLException;
     17 import java.net.URL;
     18 
     19 import okhttp3.OkHttpClient;
     20 import okhttp3.Request;
     21 import okhttp3.Response;
     22 
     23 public class MainActivity extends AppCompatActivity implements View.OnClickListener{
     24 
     25     TextView responseText;
     26 
     27     @Override
     28     protected void onCreate(Bundle savedInstanceState) {
     29         super.onCreate(savedInstanceState);
     30         setContentView(R.layout.activity_main);
     31         Button sendRequest = (Button) findViewById(R.id.send_request);
     32         responseText = (TextView) findViewById(R.id.response_text);
     33         sendRequest.setOnClickListener(this);
     34     }
     35 
     36     @Override
     37     public void onClick(View v) {
     38             if (v.getId()==R.id.send_request){
     39                 //sendRequestWithHttpURLConnection();
     40                 sendRequestWithOkHttp();
     41             }
     42     }
     43 
     44     private void sendRequestWithOkHttp() {
     45         new Thread(new Runnable() {
     46             @Override
     47             public void run() {
     48                 OkHttpClient client = new OkHttpClient();
     49                 Request request = new Request.Builder()
     50                         .url("https://www.baidu.com")
     51                         .build();
     52                 try {
     53                     Response response = client.newCall(request).execute();
     54                     String responseData = response.body().string();
     55                     showResponse(responseData);
     56                 } catch (IOException e) {
     57                     e.printStackTrace();
     58                 }
     59             }
     60         }).start();
     61 
     62     }
     63 
     64     private void sendRequestWithHttpURLConnection() {
     65         //开启线程来发起网络请求
     66         new Thread(new Runnable() {
     67             @Override
     68             public void run() {
     69                 HttpURLConnection connection = null;
     70                 BufferedReader reader = null;
     71                 try {
     72                     URL url = new URL("https://www.baidu.com");
     73                     connection =(HttpURLConnection) url.openConnection();
     74                     connection.setRequestMethod("GET");
     75                     connection.setConnectTimeout(8000);
     76                     connection.setReadTimeout(8000);
     77                     InputStream in = connection.getInputStream();
     78                     //下面对获取到的输入流进行读取
     79                     reader = new BufferedReader(new InputStreamReader(in));
     80                     StringBuilder response = new StringBuilder();
     81                     String line;
     82                     while ((line = reader.readLine())!=null){
     83                         response.append(line);
     84                     }
     85                     showResponse(response.toString());
     86                 } catch (Exception e) {
     87                     e.printStackTrace();
     88                 }finally {
     89                     if (reader != null){
     90                         try {
     91                             reader.close();
     92                         } catch (IOException e) {
     93                             e.printStackTrace();
     94                         }
     95                     }
     96                     if (connection!=null){
     97                         connection.disconnect();
     98                     }
     99                 }
    100             }
    101         }).start();
    102     }
    103 
    104     private void showResponse(final String response) {
    105         runOnUiThread(new Runnable() {
    106             @Override
    107             public void run() {
    108                 //在这里进行UI操作,将结果显示到界面上
    109                 responseText.setText(response);
    110             }
    111         });
    112     }
    113 }
  • 相关阅读:
    Caused by: Unable to load bean: type: class:com.opensymphony.xwork2.ObjectFactory
    nable to load bean: type:com.opensymphony.xwork2.util.ValueStackFactory
    一个web项目web.xml的配置中<context-param>配置作用
    js获取form的方法
    HTML <legend> 标签
    Struts2 文件上传 之 文件类型 allowedTypes
    Struts2验证框架的配置及validation.xml常用的验证规则
    struts2学习笔记--使用Validator校验数据
    LeetCode204:Count Primes
    《采访中收集程序猿》学习记录5
  • 原文地址:https://www.cnblogs.com/znjy/p/14909024.html
Copyright © 2011-2022 走看看