安卓中使用OkHttp发送数据请求的两种方式(同、异步的GET、POST) 示例-- Android基础

时间:2023-12-27 13:20:25

1、首先看一下最终效果的截图,看看是不是你想要的,这个年代大家都很忙,开门见山很重要!

安卓中使用OkHttp发送数据请求的两种方式(同、异步的GET、POST) 示例-- Android基础

简要说下,点击不同按钮可以实现通过不同的方式发送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>