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

 更新时间:2018年01月30日 09:36:53   作者:a_fly_pig  
下面小编就为大家分享一篇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两种获取网络数据的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Android中ListView下拉刷新的实现方法实例分析

    Android中ListView下拉刷新的实现方法实例分析

    这篇文章主要介绍了Android中ListView下拉刷新的实现方法,涉及Android操作ListView的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-10-10
  • Android使用Item Swipemenulistview实现仿QQ侧滑删除功能

    Android使用Item Swipemenulistview实现仿QQ侧滑删除功能

    大家都用过QQ,肯定有人好奇QQ滑动删除Item的效果是怎样实现的,其实我们使用Swipemenulistview就可以简单的实现。这篇文章主要介绍了Android使用ItemSwipemenulistview实现仿QQ侧滑删除功能,需要的朋友可以参考下
    2017-02-02
  • Android仿淘宝商品详情页效果

    Android仿淘宝商品详情页效果

    这篇文章主要为大家详细介绍了Android仿淘宝商品详情页效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-10-10
  • Android单项绑定MVVM项目模板的方法

    Android单项绑定MVVM项目模板的方法

    这篇文章主要给大家介绍了关于Android单项绑定MVVM项目模板的相关资料,文中通过示例代码介绍的非常详细,对各位Android开发者们具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-04-04
  • Android仿QQ空间顶部条背景变化效果

    Android仿QQ空间顶部条背景变化效果

    这篇文章主要介绍了Android仿QQ空间顶部条背景变化效果 ,qq空间的这个页面其实很简单,感兴趣的朋友跟随脚本之家小编一起看看吧
    2018-04-04
  • Android卫星菜单效果的实现方法

    Android卫星菜单效果的实现方法

    这篇文章主要介绍了Android卫星菜单效果的实现方法,需要的朋友可以参考下
    2017-05-05
  • Android UI控件之ProgressBar进度条

    Android UI控件之ProgressBar进度条

    这篇文章主要为大家详细介绍了Android UI控件之ProgressBar进度条的实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-12-12
  • Android NavigationBar问题处理的方法

    Android NavigationBar问题处理的方法

    本篇文章主要介绍了Android NavigationBar问题处理的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • Android开发中的错误及解决办法总结

    Android开发中的错误及解决办法总结

    本文属于个人平时项目开发过程遇到的一些问题,记录下来并总结解决方案,希望能帮到大家解决问题,需要的朋友可以参考下
    2022-02-02
  • Android录音mp3格式实例详解

    Android录音mp3格式实例详解

    本文讲述了Android录音成MP3格式实现思路概述,需要的朋友可以参考下
    2018-03-03

最新评论