Android14-发送网络请求

1. WebView的用法

  • 以下代码演示使用WebView加载一个网页

    注:使用WebView需要在Manifest文件中声明网络请求的权限

      <uses-permission android:name="android.permission.INTERNET"/>
    
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        //获得webView
        WebView webView = (WebView) findViewById(R.id.web_view);
        //通过调用getSettings()设置浏览器的属性,这里的setJavaScriptEnabled()方法设置了,
        // webView支持JavaScript脚本
        webView.getSettings().setJavaScriptEnabled(true);
        //设置打开新的网页时仍在当前的webView打开,而不是去启动系统浏览器
        webView.setWebViewClient(new WebViewClient());
        //设置webView要加载的网页链接
        webView.loadUrl("http://www.baidu.com");
    }
}

2. 发送网络请求

  1. 使用HttpURLConnection发送网络请求

1.第一步:new一个URL对象

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

2.第二步:设置HTTP请求所使用的方法(GET或POST)

connection.setRequestMethod("GET");

3.第三步:设置一些自由的定制,比如设置连接超时、读取超时的毫秒数、以及服务器希望得到的一些消息头等、可以根据自己的实际情况进行编写。

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

4.第四步:调用getInputStream()方法获取服务器返回的输入流。

InputStream in = connection.getInputStream();

5.第五步:调用disconnect()方法将这个HTTP连接关闭掉。

connection.disconect();
  • 以下代码演示了发送一个网络请求,并将返回的结果展示在TextView上
public class MainActivity extends AppCompatActivity {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        Button sentRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sentRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sentRequestWithHttpURLConnection();
            }
        });
    }

    private void sentRequestWithHttpURLConnection() {
        //开启线程发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    //初始化url
                    URL url = new URL("http://guolin.tech/api/china/23/223");
                    //初始化connection
                    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);
                    }
                    showRespons(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }

    private void showRespons(final String respons) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //在这里进行UI操作,将结果显示在界面上
                responseText.setText(respons);
            }
        });
    }
}

2.使用OkHttp发送网络请求

OkHttp是由Square公司开发的开源项目,简单易用,功能强大,是广大Android开发者首选的网络通信库。

  • 在使用OkHttp之前,需要现在项目中添加OkHttp库的依赖,添加之后会自动下OkHttp和Okio库,Okio库是通信的基础。
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    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.6.0'
}
  • 具体使用方法如下:

1.创建一个OkHttpClient实例

OkHttpClient client = new OkHttpClient();

2.如果要发起HTTP请求,需要创建一个Request对象,并在此设置相关属性

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

3.之后调用OkHttpClient的newCall()方法来创建一个Call对象,并调用它的execute()方法来获取服务器返回的数据

Response response = client.newCall(request).execute();
  • 使用OkHttp发送一个完整的网络请求代码如下
    private void sendRequestWithOkHttp() {
   //在子线程中发起网络请求
   new Thread(new Runnable() {
       @Override
       public void run() {
           try {
                //实例化一个OkHttpClient对象
               OkHttpClient client = new OkHttpClient();
               //实例化一个Request对象
               Request request = new Request.Builder()
//                            .url("http://10.0.2.2/get_data.xml")
                       .url("http://10.0.2.2/get_data.json")
                       .build();
                //发起网络请求并获得服务器返回的数据
               Response response = client.newCall(request).execute();
               String responseData = response.body().string();
           } catch (Exception e) {
               e.printStackTrace();
           }
       }
   }).start();
}
  • 运行结果如下
2017-04-14_10-21-03.gif

[图片上传失败...(image-4969de-1527935021418)]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,086评论 19 139
  • 这篇文章主要讲 Android 网络请求时所使用到的各个请求库的关系,以及 OkHttp3 的介绍。(如理解有误,...
    小庄bb阅读 1,380评论 0 4
  • 一.网络通信概念理解 1.http协议概述 当我们在自己电脑的web浏览器地址栏敲入网址url,点击enter,...
    铜雀春深锁不住阅读 5,142评论 0 3
  • 通常内向者,就被贴了标签,觉得在沟通上就是不行,今天我们来说说怎么做可以做些改变! 先来说说内向性格,其实我们每个...
    梁明月创业笔记阅读 150评论 2 3
  • 凌晨一点醒来'嗯'是疼醒的'今早出门摔了一跤'膝盖处'白天一直隐隐作痛'没想到到了晚上'弯曲不得'躺直也难受'恨不...
    小幸运_c2ac阅读 335评论 0 1

友情链接更多精彩内容