您的位置:首页 > 理论基础 > 计算机网络

《第一行代码》第二版 学习总结25 OkHttp基本使用

2018-03-26 22:09 525 查看
      最近利用下班时间,找了看什么书比较适合初学android的朋友,很多人推荐了这本书,于是就买了一本,感觉看书,思考,动手,再思考和总结这样过程还是很有必要的,于是就打算把自己学习的东西简单的总结一下;方便自己以后查找,也有利于学习的巩固。在这里首先要感谢一下书籍的作者——郭霖前辈。
[b]      Android App如果没有网络的支持,就会显得非常的单薄,本地的资源相较于互联网上的丰富世界差太远了。现在还有很多数据处理都是放在云端处理,本地只负责提供数据和接受数据,说到这里,又想起来研究生时期老师让我们研究的课题了,就是均衡本地与云端数据处理。想想还是蛮怀恋的。好了,不多说了;关于Android网络这一块,我也会就和书本给出以下几块内容------WebView基本使用HttpURLConnection基本使用,OkHttp基本使用,XML文件两种解析方式(Pull和Sax),JSON解析相关以及最后的综合示例代码
[/b]

[b]1,OkHttp简介[/b]
      上一部分简单介绍了HttpURLConnection的基本使用,今天就来介绍一个在Github上一直以来很火的开源项目——OkHttp;该项目由Square开发,是广大Android开发者首选的网络通信库。开源项目链接本文示例代码链接
[b]使用步骤:[/b]
第一步:依赖Jar文件配置
(1)下载开源项目,找到Jar文件直接添加
(2)修改gradle文件,同步运行一下实现Jar文件下载添加
第二步:获取OkHttpClient实例
第三步:构建请求Request对象——类似构建通知实例对象
第四步:获取Call实例,调用execute()方法,获取返回数据
第五步:解析返回数据用于处理其他逻辑

[b]2,示例代码[/b]

[b]MainActivity.java代码:[/b]
package com.hfut.operationokhttp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";
EditText url;
TextView webContent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
}

private void initUI() {
url = findViewById(R.id.web_url);
webContent = findViewById(R.id.display_webContent);
}

/**
* 第一步:获取OkHttpClient实例
* 第二步:创建请求request
* 第三步:获取Call对象,通过OkHttpClient.newCall()
* 第四步:执行Call对象的execute()方法,获取返回数据
* 第五步:处理返回数据
*/

public void querySourceCode(View view) {

new Thread(new Runnable() {
@Override
public void run() {
String tempUrl = url.getText().toString();
if (!TextUtils.isEmpty(tempUrl)) {
if (isUseableURL(tempUrl)) {
tempUrl="http://"+tempUrl;
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(tempUrl)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
if (response.code() == 200) {
String tempResult = response.body().string();
showResult(tempResult);
} else {
showResult("响应状态码错误,无法获取数据");
}
} catch (IOException e) {
e.printStackTrace();

}
} else {
showResult("网址输入不正确");
}
} else {
showResult("请正确输入网址");
}
}
}).start();

}
//测试url是否有效
private boolean isUseableURL(String url) {
boolean flag = true;
try {
Process process = Runtime.getRuntime().exec("ping -c 1 -w 100 " + url);
int connectionStatus = process.waitFor();
if (connectionStatus != 0) {
flag = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}

private void showResult(final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
webContent.setText(s);
}
});

}
}
[b]activity_main.xml代码:[/b]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hfut.operationokhttp.MainActivity">

<EditText
android:id="@+id/web_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:hint="请在此处输入要查看源码的网址"
android:textSize="20dp" />

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="querySourceCode"
android:layout_marginTop="10dp"
android:text="查看网页源码"
android:textSize="20dp" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/display_webContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="此处显示网页源码内容" />
</ScrollView>

</LinearLayout>
/app/build.gradle文件代码:
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.hfut.operationokhttp"
minSdkVersion 22
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
}
主配置AndroidManifest.xml文件代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hfut.operationokhttp">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
3,运行结果
第一步:打开程序
                              



第二步:输入“www.baidu.com”,点击“查看网页源码”
                              



第三步:输入“why”[b],点击“查看网页源码”[/b]
[b]                              


[/b]
第四步:输入“”[b],点击“查看网页源码”[/b]
[b]                               


[/b]

[b]总结:我在读取Url地址的之后,在构建Request对象之前,添加了一个网址是否有效的判断。OkHttp功能很强大,我掌握的很少很少,也没有在实际的项目中使用过,不过我使用在其基础之上重新写的一个开源项目OkHttpTiger,当时在做自动更新下载安装应用的时候使用的。[b]本文示例代码链接[/b][/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐