安卓中使用OkHttp发送数据请求的两种方式(同、异步的GET、POST) 示例-- Android基础
1、首先看一下最终效果的截图,看看是不是你想要的,这个年代大家都很忙,开门见山很重要!

简要说下,点击不同按钮可以实现通过不同的方式发送OkHttp请求,并返回数据,这里请求的是网页,所以返回的都是些网页的代码。
2、下面给出代码,代码的实现步骤要点已经在代码行中加了注释,不过多赘述。
MainActivity.java:
package thonlon.example.cn.simpleokhttpdemo; import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast; import java.io.IOException; import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private TextView tv;
private Button btn_async_request, btn_sync_request, btn_async_post, btn_sync_post; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
} /**
* 初始化视图
*/
public void initView() {
tv = (TextView) findViewById(R.id.tv);
btn_async_request = (Button) findViewById(R.id.btn_async_request);
btn_sync_request = (Button) findViewById(R.id.btn_sync_request);
btn_async_post = (Button) findViewById(R.id.btn_async_post);
btn_sync_post = (Button) findViewById(R.id.btn_sync_post); btn_async_request.setOnClickListener(this);
btn_sync_request.setOnClickListener(this);
btn_async_post.setOnClickListener(this);
btn_sync_post.setOnClickListener(this);
} /**
* 点击事件
* @param view
*/
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_async_request:// 执行get方式的异步请求
getAsyncRequest();
break;
case R.id.btn_sync_request://执行get方式的同步请求
getSyncRequest();
break;
case R.id.btn_async_post://执行post方式的异步请求
postAsynsRequest();
break;
case R.id.btn_sync_post://执行post方式的同步请求
postSyncRequest();
break;
}
} /**
* 输出内容到TextView
* @param request
*/
public void showRequest(final String request) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(request);
}
});
}
/**
* 发送异步GET请求
*/
private void getAsyncRequest() {
//创建OkHttpClient对象
OkHttpClient okhttpClient = new OkHttpClient();
//创建Request对象
Request request = new Request.Builder()
.url("https://www.haha.mx/joke/2730898")//请求的地址,根据需求带参
.build();
//创建call对象
Call call = okhttpClient.newCall(request);
call.enqueue(new Callback() {
/**
* 请求失败后执行
* @param call
* @param e
*/
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(MainActivity.this,"异步get方式请求数据失败!",Toast.LENGTH_LONG).show();
} /**
* 请求成功后执行
* @param call
* @param response
* @throws IOException
*/
@Override
public void onResponse(Call call, Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,"异步get方式请求数据成功!",Toast.LENGTH_LONG).show();
showRequest(res);
}
});
}
});
} /**
* 发送同步的get请求
*/
public void getSyncRequest() {
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("http://hibernate.org/orm/releases/5.3/")
.build();
try {
Response response = okHttpClient.newCall(request).execute();
String responseResult = response.body().string();
showRequest(responseResult);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} /**
* 发送异步post()请求
*/
private void postAsynsRequest() {
OkHttpClient okhttpClient = new OkHttpClient();
FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
formBody.add("usernam", "Thanlon");
formBody.add("password", "123");
Request request = new Request.Builder()
.url("https://www.baidu.com")
.post(formBody.build())
.build();
Call call2 = okhttpClient.newCall(request);
call2.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(MainActivity.this,"异步post请求数据失败!",Toast.LENGTH_LONG).show();
} @Override
public void onResponse(Call call, Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,"post异步请求数据成功!",Toast.LENGTH_LONG).show();
showRequest(res);
}
});
}
});
} /**
* 发送同步的post请求
*/
public void postSyncRequest() {
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient okHttpClient = new OkHttpClient();
FormBody.Builder formBody = new FormBody.Builder();
formBody.add("username", "Thanlon");
formBody.add("password", "123");
Request request = new Request.Builder()
.url("https://www.douban.com")
.post(formBody.build())
.build();
try {
Response response = okHttpClient.newCall(request).execute();
String responseResult = response.body().string();
showRequest(responseResult);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="thonlon.example.cn.simpleokhttpdemo.MainActivity"> <TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示请求后的信息"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.4" /> <Button
android:id="@+id/btn_async_request"
android:layout_width="0dp"
android:layout_height="50dp"
android:text="发送request异步请求"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" /> <Button
android:id="@+id/btn_sync_request"
android:layout_width="0dp"
android:layout_height="50dp"
android:text="发送request同步请求"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.1" /> <Button
android:id="@+id/btn_async_post"
android:layout_width="0dp"
android:layout_height="50dp"
android:text="发送post异步请求"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.2" /> <Button
android:id="@+id/btn_sync_post"
android:layout_width="0dp"
android:layout_height="50dp"
android:text="发送post同步请求"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.3" /> </android.support.constraint.ConstraintLayout>
安卓中使用OkHttp发送数据请求的两种方式(同、异步的GET、POST) 示例-- Android基础的更多相关文章
- .Net Core下发送WebRequest请求的两种方式
1.使用RestSharp.NetCore 2.使用WebApi请求方式
- C#中Post请求的两种方式发送参数链和Body的
POST请求 有两种方式 一种是组装key=value这种参数对的方式 一种是直接把一个字符串发送过去 作为body的方式 我们在postman中可以看到 sfdsafd sdfsdfds publi ...
- 数据存储的两种方式:Cookie 和Web Storage
数据存储的两种方式:Cookie 和Web Storage 1.Cookie Cookie的作用就像你去超市购物时,第一次给你办张购物卡,这个购物卡里存放了一些你的个人信息,下次你再来这个连锁超市时, ...
- 数据存储的两种方式:Cookie 和Web Storage(转)
数据存储的两种方式:Cookie 和Web Storage 数据存储的两种方式:Cookie 和Web Storage 1.Cookie Cookie的作用就像你去超市购物时,第一次给你办张购物卡 ...
- 第二节:SSL证书的申请、配置(IIS通用)及跳转Https请求的两种方式
一. 相关概念介绍 1. SSL证书服务 SSL证书服务由"服务商"联合多家国内外数字证书管理和颁发的权威机构.在xx云平台上直接提供的服务器数字证书.您可以在阿里云.腾讯云等平台 ...
- 解决 SharePoint 2010 拒绝访问爬网内容源错误的小技巧(禁用环回请求的两种方式)
这里有一条解决在SharePoint 2010搜索爬网时遇到的“拒绝访问错误”的小技巧. 首先要检查默认内容访问帐户是否具有相应的访问权限,或者添加一条相应的爬网规则.如果目标资源库是一个ShareP ...
- Android中EditText显示明文与密文的两种方式
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 记录输入框显示.隐藏密码的简单布局以及实现方式. 效果图 代码分析 方式一 /**方式一:*/ private void sh ...
- 在eclipse中使用Maven建web工程的两种方式
Eclipse版本:Neon Release (4.6.0) Maven版本:3.3.9 第一种方式: 右键新建maven工程,勾选创建一个简单工程 填入信息,注意打包方式要改为war 点击完成,创建 ...
- PHP发送HTTP请求的几种方式
转发:https://blog.tanteng.me/2017/07/php-curl-guzzlehttp/ 1)PHP开发中我们常用CURL 方式封装 HTTP请求,什么是CURL? CURL 是 ...
随机推荐
- VC++ 获取exe或者dll版本信息
#include <iostream> #include <atlstr.h> #pragma comment(lib,"version.lib") CSt ...
- 从输入URL到页面显示发生了什么
阅读目录 1.输入地址 2.浏览器查找域名的 IP 地址 3.浏览器向 web 服务器发送一个 HTTP 请求 4.服务器的永久重定向响应 5.浏览器跟踪重定向地址 6.服务器处理请求 7.服务器返回 ...
- django基础 -- 9.中间件
一.中间件的介绍 中间件顾名思义,是介于request与response处理之间的一道处理过程,相对比较轻量级, 并且在全局上改变django的输入与输出.因为改变的是全局,所以需要谨慎实用, 用不好 ...
- PowerDesigner 学习:十大模型及五大分类
个人认为PowerDesigner 最大的特点和优势就是1)提供了一整套的解决方案,面向了不同的人员提供不同的模型工具,比如有针对企业架构师的模型,有针对需求分析师的模型,有针对系统分析师和软件架构师 ...
- 配置named服务之前的 相关术语意思
putty: [p^ti]: 油灰, 腻子,像 clay 粘土一样起 连接作用. 非常简洁,只有500多kB, 不需要安装,纯绿色的,版本还是0.x, Simon Tatham, 甚至没有主界面,没有 ...
- kubernetes 实战4_命令_Configure Pods and Containers
Configure Service Accounts for Pods A service account provides an identity for processes that run in ...
- XMatch: 您的部门管理助手
本博客为XMatch项目宣传博客. XMatch: 您的部门管理助手 目录 一.产品概述 二.产品功能 三.产品的创新特色 四.推广方案 五.宣传图 一.产品概述 当前社团的各方面管理工作主要都由手工 ...
- forEach、map、filter、find、sort、some等易错点整理
一.常用方法解析 说起数组操作,我们肯定第一反应就是想到forEach().map().filter()等方法,下面分别阐述一下各方法的优劣. 1.forEach 1.1 基础点 forEac ...
- Python lambda 表达式
def ds(x): *x+ print(ds()) g = lambda x:*x+ print(g()) #------------ def sf(a,b): return a+b print(s ...
- 函数指针-如何理解typedef void (*pfun)(void)
问题: 在刚接触typedef void (*pfun)(void) 这个结构的时候,存在疑惑,为什么typedef后只有一"块"东西,而不是两"块"东西呢?那 ...