Android笔记-使用okhttp3库发送http请求

Posted IT1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android笔记-使用okhttp3库发送http请求相关的知识,希望对你有一定的参考价值。

build.gradle新加:

implementation 'com.squareup.okhttp3:okhttp:3.8.0'

 在androidManifest.xml添加权限

<uses-permission android:name="android.permission.INTERNET"/>
 

 

源码如下:

HttpRequest.java

package com.example.myclient.http;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class HttpRequest {

    private Call mCall;

    public HttpRequest(String url) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .get()
                .url(url)
                .build();
        mCall = client.newCall(request);
    }

    public void request(Callback callback){

        if(mCall != null){

            if(mCall.isExecuted()){

                mCall.clone().enqueue(callback);
            }
            else{

                mCall.enqueue(callback);
            }
        }
    }
}

MainActivity.java

package com.example.myclient;

import android.os.Bundle;

import com.example.myclient.http.HttpRequest;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static final String URL = "http://192.168.20.59/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        final HttpRequest request = new HttpRequest(URL);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                request.request(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                        Log.e("error", "请求失败");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        Log.e("success", "请求成功:" + response.body().string());
                    }
                });
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

源码打包下载地址:

https://github.com/fengfanchen/AndroidReverse/tree/master/OkHttp3Demo

以上是关于Android笔记-使用okhttp3库发送http请求的主要内容,如果未能解决你的问题,请参考以下文章

url编码okhttp3 android删除%20

基本使用——OkHttp3详细使用教程

Android 使用Retrofit2.0+OkHttp3.0实现缓存处理+Cookie持久化第三方库

关于Okhttp3api使用

Android项目中okhttp3的简易封装和使用

无法通过 Android 发送 Firebase 通知,但可以通过 curl 工作