OKHttp之Post请求案例

本文介绍了高效HTTP客户端OKHttp的核心特性,如连接池、拦截器和透明GZIP压缩,并指出其已被Google采纳。相较于已过时的android-async-http库,OKHttp支持更低的Android版本和Java版本。文中提供了一个使用OKHttp进行POST请求的示例,包括添加依赖、配置清单文件和主方法的实现。
摘要由CSDN通过智能技术生成

简介

 

OKHttp是一款高效的HTTP客户端,支持连接同一地址的链接共享同一个socket,通过连

接池来减小响应延迟,还有透明的GZIP压缩,请求缓存等优势,其核心主要有路由

接协议拦截器代理安全性认证连接池以及网络适配,拦截器主要是++指添加,

移除或者转换请求或者回应头部信息++

这个库也是square开源的一个网络请求库(okhttp内部依赖okio)。现在已被Google使用

在Android源码上了,可见其强大。

关于网络请求库,现在应该还有很多人在使用android-async-http。他内部使用的是

HttpClient,但是Google在6.0版本里面删除了HttpClient相关API,可见这个库现在有

点过时了。

OkHttp最低支持Android2.3,最低支持java1.7.

下面写一个用post请求接口的demo:

1.添加依赖:导依赖的时候注意AS的版本问题。

recyclerview依赖:

  compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
OKhttp依赖:
  compile 'com.squareup.okhttp3:okhttp:3.9.0'
gson依赖:
  compile 'com.google.code.gson:gson:2.8.1'
glide依赖:
 compile 'com.github.bumptech.glide:glide:3.7.0'
okhttp依赖:
 compile 'com.squareup.okio:okio:1.5.0'
okhttp拦截器依赖:
 compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

2.清单文件

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

3.mainactivity.xml

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview2"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v7.widget.RecyclerView>

item布局文件:
 <TextView
        android:id="@+id/tv1"
        android:text="654651651651651651"
        android:textSize="25sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
<ImageView
    android:id="@+id/img"
    android:src="@mipmap/ic_launcher"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

mainActivity主方法:

public class SecondActivity extends AppCompatActivity {
    private RecyclerView recyclerView2;
   //数据集合 
   List<Bean.ResultBean.DataBean> list = new ArrayList<>();
   //handler实例化
    Handler handler1 = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        //初始化控件
        recyclerView2 = (RecyclerView) findViewById(R.id.recyclerview2);
       //布局管理器
       LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView2.setLayoutManager(manager);
        initData();
    }
    //post请求网络数据
    private void initData() {
     //接口
    String path = "http://apis.juhe.cn/cook/query.php";

      OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.MINUTES)
                .readTimeout(5, TimeUnit.MINUTES)
                .build();
        FormBody formBody = new FormBody.Builder()
                .add("menu", "鱼香肉丝")
                .add("key", "77643fdff291bce1a3db9b6a74817743")
                .build();
        Request request = new Request.Builder()
                .url(path)
                .post(formBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                System.out.println(string);
                Bean bean = Bean.objectFromData(string);
                list = bean.result.data;
                handler1.post(new Runnable() {
                    @Override
                    public void run() {
                        MyAdapter adapter = new MyAdapter(SecondActivity.this, list);
                        recyclerView2.setAdapter(adapter);

                    }
                });
            }
        });
    }
}

适配器:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
   Context context;
    List<Bean.ResultBean.DataBean>list = new ArrayList<>();

    public MyAdapter(Context context, List<Bean.ResultBean.DataBean> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context,R.layout.item,null);
        ViewHolder holder = new ViewHolder(view);
        return  holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.tv.setText(list.get(position).title);
        Glide.with(context).load(list.get(position).albums.get(0)).into(holder.img);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
            ImageView img;
        TextView tv;

        public ViewHolder(View itemView) {
            super(itemView);
            tv = itemView.findViewById(tv1);
            img = itemView.findViewById(R.id.img);
        }
    }
}
Bean类:
public class Bean {


    /**
     * resultcode : 200
     * reason : Success
     * result : {"data":[{"id":"27","title":"醋溜白菜","tags":"家常菜;健脾开胃;排毒;骨质疏松;便秘;补钙;快手菜;秋季养生","imtro":"醋溜白菜,是北方人经常吃的一道菜,尤其是在多年前的冬天。那时,没有大棚菜,冬天,家家每天佐餐的基本上都是冬储大白菜,聪明的家庭主妇总是想方设法将这单调的菜变成多种菜式,于是,醋溜白菜被频繁的端上餐桌。 美食不分贵贱,用最平凡的原料、最简单的调料和最普通的手法做出美味的菜肴来才是美食的真谛。 这次,我做的醋溜白菜,近似鲁菜的做法,使个这道菜酸甜浓郁、开胃下饭、老少咸宜。","ingredients":"白菜,380g","burden":"油,适量;盐,适量;花椒,适量;干红椒,适量;葱,适量;姜,适量;蒜,适量;醋,适量;酱油,适量;糖,适量;淀粉,适量","albums":["http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/t/0/27_323249.jpg"],"steps":[{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/1/27_102bf2969f83e428.jpg","step":"1.准备食材。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/1/27_7526d75d4241598c.jpg","step":"2.将白菜斜刀片成薄片。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/1/27_e7125d31984f36d6.jpg","step":"3.片切好的白菜帮与菜叶分别入好。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/1/27_75b6d506277faa55.jpg","step":"4.盐、糖、生抽、醋淀粉加少许水调匀备用。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/1/27_31c65b8e2686f69e.jpg","step":"5.锅中油烧热,先入花椒炒香后捞出。再加入干红椒段略炒。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/1/27_e743c21e6c837450.jpg","step":"6.加入葱姜蒜煸炒香,然后入白菜帮翻炒。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/1/27_f977dace4f40339e.jpg","step":"7.炒至菜帮变软时,加入白菜叶。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/1/27_15be74a85c0b1e65.jpg","step":"8.快速翻炒至菜软,勾入碗汁"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/1/27_9f70e04418bb4b77.jpg","step":"9.使汤汁均匀的包裹在菜帮上即可"}]},{"id":"154","title":"酸辣白菜","tags":"家常菜;增强抵抗力;下饭菜;快手菜","imtro":"酸辣白菜是是老百姓餐桌上最常见的家常菜,其营养丰富,口感清脆,口味独特。是一道开胃的下饭菜。主要食材是白菜。大白菜具有较高的营养价值,对于护肤、养颜、防止女性乳腺癌、润肠排毒、促进人体对动物蛋白的吸收等,都有极大功效。","ingredients":"白菜帮,200g","burden":"油,适量;盐,适量;干辣椒,2粒;米醋,适量;生抽,适量;花椒,适量;鸡精,适量;姜,适量","albums":["http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/t/1/154_427931.jpg"],"steps":[{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/154_8850303f7d8829db.jpg","step":"1.准备好所有食材。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/154_a19d1852abb26fd0.jpg","step":"2.白菜洗净,去叶留帮。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/154_659e744a3399a0c2.jpg","step":"3.白菜帮竖着对半切开。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/154_6705b5941a774853.jpg","step":"4.用斜刀将白菜片成片。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/154_0a978d450c04049e.jpg","step":"5.辣椒剪成段,姜切末。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/154_ff27993b8861ccbf.jpg","step":"6.锅中倒入油,烧热,下入花椒爆香。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/154_4bde0d1220be49da.jpg","step":"7.放入干辣椒和姜末炒香。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/154_7091f0a80c36a1ef.jpg","step":"8.倒入白菜片,翻炒2分钟。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/154_fecbc52d0521b75b.jpg","step":"9.加入盐,米醋和生抽。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/154_3a092361ae69a32c.jpg","step":"10.搅拌均匀后加入鸡精调味即可。"}]},{"id":"200","title":"佛手白菜","tags":"家常菜;排毒;骨质疏松;咸;10-20分钟;便秘;补钙;朋友聚餐;1-2人;锅子;其他工艺","imtro":"白菜是我们生活中最普通的一个做菜的原料。白菜古时又叫菘,有\u201c菜中之王\u201d的美名。白菜的营养价值很高。含有丰富的有蛋白质、脂肪、多种维生素和钙、磷等矿物质以及大量粗纤维,有清热除烦、解渴利尿、通利肠胃的功效。秋冬季节空气特别干燥,寒风对人的皮肤伤害极大。白菜中含有丰富的维生素C、维生素E,多吃白菜,可以起到很好的护肤和养颜效果。 这道佛手白菜,做法非常简单,有荤有素而且还很清淡,很适合减肥人群食用。其特点;形如佛手,馅香可口,白菜脆嫩。是一道老少皆宜的佳肴。","ingredients":"白菜,300g;肉馅,100g","burden":"油,适量;盐,适量;葱,适量;姜,适量;姜,适量;香油,适量;生抽,适量;淀粉,适量","albums":["http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/t/1/200_468852.jpg"],"steps":[{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_c77d6a57306a857b.jpg","step":"1.肉馅中加入葱姜 盐 鸡精 香油 生抽搅拌均匀。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_c67f65f91581602c.jpg","step":"2. 加入水淀粉搅打至上劲。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_d8dc28033f6b35c6.jpg","step":"3.白菜帮洗净,切成8厘米的块。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_a119da29ee055081.jpg","step":"4.锅中烧开水,白菜帮放进去焯至透明。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_cb8a17b8b668f842.jpg","step":"5.直接捞入冷水中。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_c6e61307144f1841.jpg","step":"6.沥干水分,取一片放在盘中。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_c595a8e6280a5c0a.jpg","step":"7.从白菜帮中间均匀的划4刀。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_fbc70056fc5c0363.jpg","step":"8. 把肉馅放在上面。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_1b31f0c07c437233.jpg","step":"9. 把白菜帮折成佛手形状。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_d165debb5b3344e4.jpg","step":"10.依次做好,码放整齐。上蒸锅蒸制10分钟。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_9f5220b6a2ea0d67.jpg","step":"11. 把滤出的汤汁倒入炒锅中,芶入薄芡,淋入香油。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/2/200_4465d3799058f2e2.jpg","step":"12. 把芡汁均匀的浇在佛手菜上即可。"}]},{"id":"226","title":"醋溜白菜","tags":"家常菜;排毒;骨质疏松;酸;10分钟内;便秘;补钙;醋溜;朋友聚餐;全菜系;1-2人;炒锅","imtro":"大鱼大肉吃腻的时候,来一道醋溜白菜吧,解腻又去油~ 酸辣适中,开胃爽口。","ingredients":"白菜,500g","burden":"青红椒,2个;花椒,适量;陈醋,2勺;生抽,1勺;糖,1小勺;水淀粉,1勺;葱,适量;八角,适量;姜,适量;蒜,适量","albums":["http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/t/1/226_780777.jpg"],"steps":[{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/226_712e4c68b94df3d9.jpg","step":"1.白菜帮切丝,青红椒切丝,葱姜蒜切好备用"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/226_2f8cfdf157bc68c9.jpg","step":"2.热锅入油,花椒八角爆香"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/226_c7f9590343700973.jpg","step":"3.放入辣椒,葱姜蒜爆香"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/226_64f62c070e8fa2c4.jpg","step":"4.放入白菜帮,翻炒至半熟。依次放入盐,陈醋,生抽,糖调味"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/226_729db6914f9b944f.jpg","step":"5.翻炒均匀后加入白菜叶,继续翻炒至菜叶变软。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/226_4436c713ccd50fb9.jpg","step":"6.加入薄芡,翻炒均匀即可出锅。"}]},{"id":"236","title":"干煸白菜","tags":"家常菜;健脾开胃;排毒;骨质疏松;便秘;素食;补钙;干煸;春季养生","imtro":"喜欢简单的菜,一来容易上手,二来因为简单可以偷懒。其实简单的菜同样也不少费工夫,就像今天这个\u201c干煸白菜\u201d就没少费事。 简单的食材要做出味道,吃出滋味来就要费一点心思在里面。干煸白菜是我们这里的常见菜,也是很讨喜的一个菜,如果把酸辣土豆丝比喻为\u201c大众情人\u201d的话,那么干煸白菜就是\u201c梦中情人\u201d。干煸白菜因其实惠的价格,特殊的口感和味道在饭桌上赢得了众多人的青睐,白话就是极具\u201c性价比\u201d。 那就做个\u201c干煸白菜\u201d,会会这个\u201c梦中情人\u201d。","ingredients":"白菜,300g","burden":"油,适量;盐,适量;生姜,适量;红尖椒,适量;大蒜,适量","albums":["http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/t/1/236_683404.jpg"],"steps":[{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_b18793c507d869cb.jpg","step":"1.白菜去老帮洗净用刀片成薄片,白菜帮和白菜叶分开。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_72de40419de42093.jpg","step":"2.红尖椒洗净切小段。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_136bcbaf16b3d2b9.jpg","step":"3.蒜瓣切薄片。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_acc3c89db8add96d.jpg","step":"4.生姜切成细丝。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_3f539b822e9a837f.jpg","step":"5.锅里倒入少许植物油,锅热后倒入白菜帮片,小火煸炒。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_709c9521602cb1b2.jpg","step":"6.等白菜帮片稍微变软后倒入白菜叶,继续小火煸炒。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_4ea4a6cc370864bf.jpg","step":"7.等白菜炒至微带虎皮色后即可盛出,备用。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_859f6d3287e3ab4a.jpg","step":"8.锅里倒入植物油,油热后放入姜丝爆香。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_6b7e06aaee719810.jpg","step":"9.倒入蒜片,红椒爆香。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_d687d4bd1f3cd57d.jpg","step":"10.倒入白菜片,大火翻炒。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/236_9cbd270dbbf8b715.jpg","step":"11.调入精盐,炒匀即可出锅。"}]},{"id":"257","title":"蒸白菜包","tags":"家常菜;热菜;老年人;白领;增强抵抗力;冬季养生","imtro":"冬天,做这个菜,白菜是主打的当家菜,豆腐卷是买来现成的,再有就是肉馅了,一般做这个,我基本都是用上次没有吃完的,冰箱里冻着的味调好的,拿出来化开就可以包的馅,主要就是想着怎样打发它。","ingredients":"白菜,150g;豆腐卷,50g;肉馅,50g","burden":"香油,适量;生抽,适量;红萝卜,适量","albums":["http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/t/1/257_311854.jpg"],"steps":[{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/257_64a30ee21f7dbffb.jpg","step":"1.白菜、豆腐卷、肉馅、红萝卜备好待用。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/257_1594e853b18b58a4.jpg","step":"2.上煮锅,水烧开。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/257_0437ae6d0329dec3.jpg","step":"3.下白菜,用开水把白菜烫一下。"},{"img":"http://juheimg.oss-cn-hangzhou.aliyuncs.com/cookbook/s/3/257_fac41c4f6525d1d4.jpg","step":"4.捞出,
Java代码调用post接口传参的案例可以分为以下几个步骤: 1. 导入相关依赖 一般情况下,我们需要导入HTTP客户端的相关依赖,推荐使用Apache HttpComponents或OkHttp来实现HTTP请求。 2. 构造HTTP请求 根据接口文档中给出的API地址和请求方法,我们可以构造对应的HTTP请求对象,设置请求头、参数等内容。例如: ``` HttpPost httpPost = new HttpPost("http://example.com/api/user"); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); JSONObject params = new JSONObject(); params.put("name", "张三"); params.put("age", 20); StringEntity stringEntity = new StringEntity(params.toString(), ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); ``` 3. 发送请求并处理响应 使用HttpClient或OkHttpClient客户端发送请求,并阻塞等待服务器响应。一般情况下,我们需要根据响应状态码和内容类型等信息来判断请求是否成功,并解析响应内容。 ``` CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); String responseContent = EntityUtils.toString(entity, Charset.forName("UTF-8")); JSONObject responseJson = JSON.parseObject(responseContent); // 处理响应内容 } ``` 以上是Java代码调用post接口传参的基本流程,当然具体实现还需要按照实际需求进行调整。在实际项目开发中,我们也可以使用各种HTTP请求框架封装,遵循开闭原则,提高代码复用性和可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值