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使用ViewFlipper实现图片上下自动轮播的示例代码
这篇文章主要介绍了Android使用ViewFlipper实现图片上下自动轮播的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-05-05
Kotlin 封装万能SharedPreferences存取任何类型详解
这篇文章主要介绍了Kotlin 封装万能SharedPreferences存取任何类型详解的相关资料,需要的朋友可以参考下2017-05-05
Android 使用Vitamio打造自己的万能播放器(6)——在线播放(播放列表)
本文主要介绍Android Vitamino在线播放列表,这里给大家提供效果图和实例代码以便大家参考学习,希望能帮助开发Android视频播放的朋友2016-07-07
Android 进阶实现性能优化之OOM与Leakcanary详解原理
LeakCanary 是大名鼎鼎的 square 公司开源的内存泄漏检测工具。目前上大部分App在开发测试阶段都会接入此工具用于检测潜在的内存泄漏问题,做的好一点的可能会搭建一个服务器用于保存各个设备上的内存泄漏问题再集中处理2021-11-11


最新评论