OKHttp请求网络

首先添加依赖

Utils类:

import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class OkHttpUtils {
    private  MyHandler myHandler=new MyHandler();
    private static OkHttpClient okHttpClient=null;
    private OkInterface okInterface;

    //单列模式
    public static OkHttpClient getInstance(){
        if (okHttpClient==null){
            okHttpClient=new OkHttpClient();
        }
        return okHttpClient;
    }

    //OkHttp get请求
    public void okGet(String url){
        //实例化OkHttpClient
        OkHttpClient client = new OkHttpClient();
        //创建请求对象
        Request request = new Request.Builder().url(url).build();
        //创建请求队列
        Call call = client.newCall(request);
        //开始请求
        call.enqueue(new Callback() {
            //失败
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = myHandler.obtainMessage();
                msg.what=0;
                msg.obj="失败";
                myHandler.sendMessage(msg);
            }
            //成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message msg = myHandler.obtainMessage();
                msg.what=1;
                msg.obj=response.body().string();
                myHandler.sendMessage(msg);
            }
        });

    }


    //OkHttp post请求
    public void okPost(String url,Map<String,String> map){
        //实例化OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new MyInter()).build();
        //创建FormBody
        FormBody.Builder builder = new FormBody.Builder();
        //遍历map
        Set<String> keys = map.keySet();
        for (String key:keys) {
            //取出Value值
            String value = map.get(key);
            //添加到FormBody中
            builder.add(key,value);
        }
        //闭合FormBody
        FormBody body = builder.build();
        //创建请求对象
        Request request = new Request.Builder().url(url).post(body).build();
        //创建请求队列
        Call call = client.newCall(request);
        //开始请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = myHandler.obtainMessage();
                msg.what=0;
                msg.obj="失败";
                myHandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message msg = myHandler.obtainMessage();
                msg.what=1;
                msg.obj=response.body().string();
                myHandler.sendMessage(msg);
            }
        });

    }

    //创建Handler
    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 0://失败
                    //获取传递过来的值
                    String  error = (String) msg.obj;
                    //调用接口的方法
                    okInterface.error(error);
                    break;
                case 1://成功
                    //获取传递过来的值
                    String  json = (String) msg.obj;
                    //调用接口的方法
                    okInterface.success(json);
                    break;
            }
        }
    }

    //创建拦截器
    class MyInter implements Interceptor{
        @Override
        public Response intercept(Chain chain) throws IOException {
            //获取原来的body
            Request request = chain.request();
            RequestBody body = request.body();
            if (body instanceof FormBody) {
                //遍历原来的所有参数,加到新的Body里面,最后将公共参数加到新的Body
                FormBody.Builder newBuilder = new FormBody.Builder();
                for (int i = 0; i < ((FormBody) body).size(); i++) {
                    String name = ((FormBody) body).name(i);
                    String value = ((FormBody) body).value(i);

                    //放入新的
                    newBuilder.add(name, value);
                }
                //在将公共参数添加进去
                newBuilder.add("source", "android");
                FormBody newBody = newBuilder.build();
                //创建新的请求
                Request newRequest = request.newBuilder().post(newBody).build();
                Response response = chain.proceed(newRequest);
                return response;
            }
            return null;
        }
    }

    //创建接口
    public interface OkInterface{
        //请求失败的方法
        void error(String error);
        //请求成功的方法
        void success(String json);
    }

    //提供外部访问的方法
    public void getOkHttp(OkInterface okInterface){
    this.okInterface=okInterface;
    }

}


MainActivity类:
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.example.okhttp.utils.Utils;

public class MainActivity extends AppCompatActivity {
    String uriString="http://www.93.gov.cn/93app/data.do?channelId=0&startNum=0";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //Button的点击事件
    public void bu(View v){
        //实例化
        Utils utils = new Utils();
        //调用解析json的方法
        utils.okhttp(uriString);
        //调用接口的外部方法
        utils.getokhttp(new Utils.HttpGet() {
            //重写的失败的方法
            @Override
            public void error(String error) {
                Toast.makeText(MainActivity.this,error,Toast.LENGTH_SHORT).show();

            }
            //重写成功的方法
            @Override
            public void success(String json) {
                Toast.makeText(MainActivity.this,json,Toast.LENGTH_SHORT).show();
            }
        });
    }
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用OkHttp请求网络图片并显示的Android程序示例: 1. 添加依赖 在你的`build.gradle`文件中添加以下依赖: ``` implementation 'com.squareup.okhttp3:okhttp:4.9.1' implementation 'com.squareup.picasso:picasso:2.71828' ``` 2. 请求网络图片 在你的Activity或Fragment中,使用以下代码请求网络图片并将其显示在ImageView中: ``` OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://www.example.com/image.jpg") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { final Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream()); // 更新UI runOnUiThread(new Runnable() { @Override public void run() { ImageView imageView = findViewById(R.id.imageView); imageView.setImageBitmap(bitmap); } }); } else { throw new IOException("Unexpected code " + response); } } }); ``` 3. 使用Picasso简化代码 你也可以使用Picasso来简化代码。它是一个强大的图片加载库,可以从URL、文件或资源加载图片,并在ImageView中显示它们。 添加依赖后,你只需要使用以下代码即可加载图片: ``` Picasso.get().load("https://www.example.com/image.jpg").into(imageView); ``` 这将使用OkHttp请求网络图片,并将其显示在ImageView中。Picasso还提供其他功能,如调整大小、缓存和转换。你可以查看官方文档了解更多信息:https://square.github.io/picasso/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值