Android网络框架:OkHttp

一.网络框架:OkHttp

OKHttp是一个处理网络请求的开源项目,是安卓端的一种轻量级框架,由移动支付Square公司贡献

二.get方法

“get”方法提交的数据会直接填充在请求报文的URL上,
如“https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1 "。
“?”问号划分域名和get提交的参数,A=B中的A是参数名,B是参数值,多个参数之间用&进行分割,如果参数值是中文,则会转换成诸如%ab%12加密16进制码。一般来说,浏览器处理的URL最大限度长度为1024B(不同浏览器不一样),所以GET方法提交参数长度有限制。

get服务端

package main

import (
	"github.com/gin-gonic/gin"
)


func main() {
	router := gin.Default()
	router.GET("/sms",getResponseJson)
	router.Run(":9090")
}

func getResponseJson(context *gin.Context) {
	name :=context.Query("name")
	pass :=context.Query("pass")
	context.JSON(200,gin.H{
		"response":"【"+name+"】"+
		"的密码是:"+pass,
	})
}

三.post方法

“post”:向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据包含在请求体中。get安全性非常低,post安全性较高。

post服务器端

package main

import (
	"github.com/gin-gonic/gin"
)



func main(){
	router := gin.Default()
	router.POST("/sms",postResponseJson)
	router.Run(":9090")
}

func postResponseJson(context *gin.Context){
	name := context.DefaultPostForm("name","用户名")
	pass := context.DefaultPostForm("pass","密码")
	context.JSON(200,gin.H{
		"smsHead":"["+name+"]的密码是:" ,
		"smsBody":pass,
	})
} 

四.安卓端

导入依赖

//okHttp
implementation("com.squareup.okhttp3:okhttp:4.9.0")
// https://mvnrepository.com/artifact/com.alibaba/fastjson
implementation group: 'com.alibaba', name: 'fastjson', version: '1.2.75'

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/tv_con"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">
            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="账号:"
                android:textSize="20sp"/>
            <EditText
                android:id="@+id/et_user"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="3"
                />

        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">
            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="密码:"
                android:textSize="20sp"
                />
            <EditText
                android:id="@+id/et_pass"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="3"
                android:inputType="textPassword"
                />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <Button
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:id="@+id/bt_get"
            tools:ignore="NestedWeights"
            android:text="@string/getRequest"
            android:textSize="20sp"
            android:onClick="sendGet"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:id="@+id/bt_post"
            android:text="@string/postRequest"
            android:textSize="20sp"
            android:onClick="sendPost"
            />
    </LinearLayout>

</LinearLayout>

类文件

MainActivity

public class MainActivity extends AppCompatActivity {

    private EditText etUser,etPass;
    private TextView tvCon;
    private static final int GET_SUCCESS = 0x001;
    private static final int POST_SUCCESS = 0x002;
    private static final int FAIL = 0x003;
    private static String path = "http://192.168.1.106:9090/sms?";
    private OkHttpClient mokHttpClient = new OkHttpClient();

    //使用handler接受传回的消息
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //使用get请求的方法
            if(msg.what == GET_SUCCESS){
                try {
                    JSONObject jsonObject = JSONObject.parseObject(msg.obj.toString());
                    GetResponseEntity getResponseEntity = JSON.toJavaObject(jsonObject, GetResponseEntity.class);
                    tvCon.setText(getResponseEntity.getResponse()+"\n");
                }catch (Exception e){
                    tvCon.setText("请求失败\n");
                }
            }
            //使用post请求的方法
            if(msg.what == POST_SUCCESS){
                try{
                    JSONObject jsonObject = JSONObject.parseObject(msg.obj.toString());
                    PostResponseEntity postResponseEntity = JSON.toJavaObject(jsonObject,PostResponseEntity.class);
                    tvCon.setText(postResponseEntity.getSmsHead() + postResponseEntity.getSmsBody() + "\n");
                }catch (Exception e){
                    tvCon.setText("请求失败\n");
                }
            }
            //请求失败
            if(msg.what == FAIL){
                tvCon.setText(msg.obj.toString());
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvCon = findViewById(R.id.tv_con);
        etPass = findViewById(R.id.et_pass);
        etUser = findViewById(R.id.et_user);
    }

    /**
     * 使用okHttp框架的get请求发送消息
     * @param view 视图
     */
    public void sendGet(View view) {
        Request.Builder builder = new Request.Builder();
        //get请求的url
        String url = path + "name=" + pathEncode(etUser.getText().toString()) + "&pass=" + pathEncode(etPass.getText().toString());
        builder.url(url);
        Request request = builder.build();
        final Message message = new Message();
        Call call = mokHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            //请求失败
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                message.what = FAIL;
                message.obj = "请求失败" + e.getMessage();
                mHandler.sendMessage(message);

            }

            //请求成果
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                message.what = GET_SUCCESS;
                message.obj = response.body().string();
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 对传入的字符串进行编码
     * @param content 待编码内容
     * @return 返回编码
     */
    private String pathEncode(String content){
        String encode = null;
        try {
            //使用UTF-8编码
            encode = URLEncoder.encode(content,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encode;
    }

    /**
     * 使用okHttp框架的post请求
     * @param view 视图
     */
    public void sendPost(View view) {
        Request.Builder builder = new Request.Builder();
        builder.url(path);
        FormBody body = new FormBody.Builder()
                .add("name",etUser.getText().toString())
                .add("pass",etPass.getText().toString())
                .build();
        builder.post(body);
        final Message message = new Message();
        final Request request = builder.build();
        Call call = mokHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                message.what = FAIL;
                message.obj = "请求失败" + e.getMessage();
                mHandler.sendMessage(message);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                message.what = POST_SUCCESS;
                message.obj = response.body().string();
                mHandler.sendMessage(message);
            }
        });
    }
}
GetResponseEntity
public class GetResponseEntity {
    private String response;

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }
}

PostResponEntity
public class PostResponseEntity {
    private String smsHead;
    private String smsBody;

    public String getSmsHead() {
        return smsHead;
    }

    public void setSmsHead(String smsHead) {
        this.smsHead = smsHead;
    }

    public String getSmsBody() {
        return smsBody;
    }

    public void setSmsBody(String smsBody) {
        this.smsBody = smsBody;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值