HttpURLConnection和okHttp两种获取网络数据的实现方法

废话少说,直接上代码。简单易懂。

xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/activity_net"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context="com.example.waterlamp.NetActivity">
 <Button
  android:id="@+id/okhttp"
  android:text="okhttp请求"
  android:layout_width="150dp"
  android:layout_height="37dp"
  android:layout_alignBottom="@+id/http"
  android:layout_alignParentEnd="true"
  android:layout_alignParentTop="true" />

 <Button
  android:id="@+id/http"
  android:text="HTTP请求"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignParentTop="true"
  android:layout_alignParentStart="true" />

 <ScrollView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_alignParentStart="true"
 android:layout_below="@+id/okhttp"
 android:layout_alignParentBottom="true"
 android:layout_alignParentEnd="true" >
  <TextView
   android:id="@+id/stringData"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />
 </ScrollView>
</RelativeLayout>

activity如下:

public class NetActivity extends AppCompatActivity implements View.OnClickListener{
private Button http,okhttp;
 private TextView stringData;
 private String web="https://www.baidu.com";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_net);
  http= (Button) findViewById(R.id.http);
  okhttp= (Button) findViewById(R.id.okhttp);
  stringData= (TextView) findViewById(R.id.stringData);
  http.setOnClickListener(this);
  okhttp.setOnClickListener(this);
 }

 @Override
 public void onClick(View v) {
  switch (v.getId()){
   case R.id.http:
    sendRequestWithHttpURLConnection();
   break;
   case R.id.okhttp:
    sendRequestWithokHttp();
   break;
  }
 }
 private void sendRequestWithHttpURLConnection(){
  new Thread(new Runnable() {
   @Override
   public void run() {
    HttpURLConnection connection=null;
    BufferedReader reader=null;
    try {
     URL url=new URL(web);
     connection= (HttpURLConnection) url.openConnection();
     connection.setRequestMethod("GET");
     connection.setConnectTimeout(5000);
     connection.setReadTimeout(5000);
     InputStream in=connection.getInputStream();
     reader=new BufferedReader(new InputStreamReader(in));
     StringBuffer response=new StringBuffer();
     String line;
     while ((line=reader.readLine())!=null){
      response.append(line);
     }
     showRespond(response.toString());
    } catch (MalformedURLException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    }finally {
     if (reader!=null){
      try {
       reader.close();
      } catch (IOException e) {
       e.printStackTrace();
      }
     }
    }
   }
  }).start();
 }

 private void showRespond(final String response) {
  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    stringData.setText(response);
   }
  });
 }
 private void sendRequestWithokHttp(){
  new Thread(new Runnable() {
   @Override
   public void run() {

    try {
     OkHttpClient client=new OkHttpClient();
     Request request=new Request.Builder()
       .url(web).build();
     Response response=client.newCall(request).execute();
     String str=response.body().string();
     showRespond(str);
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }).start();
 }
}

注意:需要在加权限

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

2.okhttp3需要在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:24.2.1'
 compile 'com.android.support:design:24.2.1'
 compile 'com.squareup.okhttp3:okhttp:3.4.1'//依赖
 testCompile 'junit:junit:4.12'
}

以上这篇HttpURLConnection和okHttp两种获取网络数据的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Android开发使用HttpURLConnection进行网络编程详解【附源码下载】

    本文实例讲述了Android开发使用HttpURLConnection进行网络编程.分享给大家供大家参考,具体如下: --HttpURLConnection URLConnection已经可以非常方便地与指定站点交换信息,URLConnection下还有一个子类:HttpURLConnection,HttpURLConnection在URLConnection的基础上进行改进,增加了一些用于操作HTTP资源的便捷方法. setRequestMethod(String):设置发送请求的方法 get

  • Android通过HttpURLConnection和HttpClient接口实现网络编程

    Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序.以下是学习中的一些经验. 1.HttpURLConnection接口 首先需要明确的是,Http通信中的POST和GET请求方式的不同.GET可以获得静态页面,也可以把参数放在URL字符串后面,传递给服务器.而POST方法的参数是放在Http请求中.因此,在编程之前,应当首先明确使用的请求方法,然后再根据所使用的方式选择相应的编程方式.HttpURLConnection是继承于URLCon

  • Android网络技术HttpURLConnection详解

    介绍 早些时候,Android 上发送 HTTP 请求一般有 2 种方式:HttpURLConnection 和 HttpClient.不过由于 HttpClient 存在 API 数量过多.扩展困难等缺点,Android 团队越来越不建议我们使用这种方式.在 Android 6.0 系统中,HttpClient 的功能被完全移除了.因此,在这里我们只简单介绍HttpURLConnection 的使用. 代码 (核心部分,目前只演示 GET 请求): 1. Manifest.xml 中添加网络权

  • Android中HttpURLConnection与HttpClient的使用与封装

    1.写在前面 大部分andriod应用需要与服务器进行数据交互,HTTP.FTP.SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议.     本文并不针对HTTP协议的具体内容,仅探讨android开发中使用HTTP协议访问网络的两种方式--HttpURLConnection和HttpClient     因为需要访问网络,需在AndroidManifest.xml中添加如下权限 <uses-permission android:name="an

  • HttpURLConnection和okHttp两种获取网络数据的实现方法

    废话少说,直接上代码.简单易懂. xml如下: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id

  • python如何获取网络数据

    Retrieving Data over HTTP Python 内置了 sockets 可以实现与网络连接并通过 Python 提取数据的功能. socket 是可以提供双向连接的,我们可以对同一个 socket 进行读写操作.比方说,A 对 socket 写入信息,并且将其发送给 socket 连接另一端 B:那么 B 读取 socket 的内容就可以得到 A 的信息.但是这样会有一个问题,比如说, A端并没有发送任何信息,而 B 端一直在尝试读取 socket 的内容,那么 A 端和 B

  • python两种获取剪贴板内容的方法

    第一种 import win32clipboard import time #速度快 容易出错 class niubi(): def lihai(self): while True: #jianting().main() t = jianting().main() print(t) class jianting(): def clipboard_get(self): """获取剪贴板数据""" win32clipboard.OpenClipboa

  • 两种获取connectionString的方式案例详解

     两种获取connectionString的方式 1. public static string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; <connectionStrings> <add name="ConnectionString" connectionString="Data Sour

  • MyBatis实现两种查询树形数据的方法详解(嵌套结果集和递归查询)

    目录 方法一:使用嵌套结果集实现 1,准备工作 2,实现代码 方法二:使用递归查询实现 树形结构数据在开发中十分常见,比如:菜单数.组织树, 利用 MyBatis 提供嵌套查询功能可以很方便地实现这个功能需求.而其具体地实现方法又有两种,下面分别通过样例进行演示. 方法一:使用嵌套结果集实现 1,准备工作 (1)假设我们有如下一张菜单表 menu,其中子菜单通过 parendId 与父菜单的 id 进行关联: (2)对应的实体类如下: @Setter @Getter public class M

  • Nodejs获取网络数据并生成Excel表格

    Nodejs的模版中有很多关于Excel表格的,这里我简单介绍一下我使用过的一个模块的使用. 首先,先安装Excel的模块: npm install node-xlsx 然后,在代码中引入模块: var xlsx = require('node-xlsx'); 最后,获取数据并写入Excel: var fs = require('fs'); var xlsx = require('node-xlsx'); var ajax = require('./ajax.js'); start(); fun

  • JS两种类型的表单提交方法实例分析

    本文实例分析了JS两种类型的表单提交方法.分享给大家供大家参考,具体如下: 1.原始的 <form method="post" action="/student/stureg/add" id="form1" onsubmit="return subForm();"> <button type="submit" class="button red" style="

  • springboot+mybatis-plus 两种方式打印sql语句的方法

    1.注解方式,yml文件配置上以下就可以直接使用 mybatis-plus: mapper-locations: classpath:mapper/*.xml configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 2.这一种网上没有,搜过好多资料都没有,我是配置多数据源,所以是在代码中写的config那么yml文件就是失效的,只能一个一个配置,到了打印sql的时候,就怎么都是找不到,后来设置的源码找到灵感,发现可

  • 详解react的两种动态改变css样式的方法

    第一种:动态添加class,以点击按钮让文字显示隐藏为demo import React, { Component, Fragment } from 'react'; import './style.css'; class Demo extends Component{ constructor(props) { super(props); this.state = { display: true } this.handleshow = this.handleshow.bind(this) thi

  • jquery的ajax和getJson跨域获取json数据的实现方法

    很多开发人员在使用jquery在前端和服务器端进行数据交互,所以很容易会认为在前端利用jquery就可以读取任何站点的数据了.近日在进行开 发时,因为要和第三方公司的一个项目进行数据的共享,因为考虑多不占用服务器的资源,遂决定直接在html进行数据的读取,不走服务器端进行中转了.然后 正好就遇到了浏览器端跨域访问的问题. 跨域的安全限制都是指浏览器端来说的,服务器端不存在跨域安全限制的问题. 目前浏览器端跨域访问常用的两种方法有两种: 1.通过jQuery的ajax进行跨域,这其实是采用的jso

随机推荐