OkHttp的使用

本文介绍如何在Android应用中利用OkHttp库进行GET和POST请求,并展示如何加载网络图片到ImageView组件中。通过具体的代码实例,展示了OkHttp的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建项目添加依赖 compile 'com.squareup.okhttp3:okhttp:3.9.0'

清单文件中加上相应的权限:<uses-permission android:name="android.permission.INTERNET"/>

在布局中activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="alice.bw.com.okhttpdemo.MainActivity">

    <Button
        android:id="@+id/get_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="get请求" />

    <Button
        android:id="@+id/post_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="post请求" />

    <Button
        android:id="@+id/img_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="加载图片" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/imageView"/>



</LinearLayout>

在java代码中MainActivity

package alice.bw.com.okhttpdemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.IOException;

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

public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
    }

    public void onClick(View view) {
        switch (view.getId()){
            case R.id.get_btn:
                getStringNet();
                break;
            case R.id.post_btn:
                postStringNet();
                break;
            case R.id.img_btn:
                getImgNet();
                break;
        }


    }

    private void getImgNet() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://pic.nipic.com/2008-05-26/200852684031634_2.jpg").get().build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            //运行在子线程中
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                byte[] b = response.body().bytes();
                final Bitmap bm = BitmapFactory.decodeByteArray(b,0,b.length);

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //运行在主线程中的
                        imageView.setImageBitmap(bm);
                    }
                });
            }
        });


    }

    private void postStringNet() {
        OkHttpClient client = new OkHttpClient();
        //post请求的字段
        RequestBody body = new FormBody.Builder().add("pageNo","1")
                .add("pageSize","20")
                .add("serialIds","2143,3404")
                .add("v","4.0.0").build();
        //获得一个 携带有地址信息的请求  带有参数的
        Request request = new Request.Builder().url("http://mrobot.pcauto.com.cn/v2/cms/channels/1?").post(body).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
            //请求成功
                Log.d("sxl", "onResponse: "+response.body().string());
            }
        });

    }

    private void getStringNet() {
        OkHttpClient okhttpclient = new OkHttpClient();
        //获得一个 携带有地址信息的请求
        Request request = new Request.Builder().url("http://a121.baopiqi.com/api/mh/getVideoClassification.php?&appname=%E7%88%B1%E6%83%85%E6%BC%AB%E7%94%BB%E7%B2%BE%E9%80%89&pkgname=com.platform.cartoonl&imei=863191020203140&versionname=1.2.7&page=0&limit=12").get().build();
        //获取一个任务
        Call call = okhttpclient.newCall(request);
        //异步请求   enqueue  //同步请求  execute
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("sxl", "onResponse: "+response.body().string());
            }
        });
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值