用OK进行网络请求的三种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Jonly_W/article/details/79952388

在调取方法传递  URl  的时候我们可以进行  先拼接好再传递 也可以 先传递在方法里面进行 拼接


package com.bawei.newokhttp;


import android.util.Log;

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

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

/**
 * Created by   on 2018/4/13.
 */

public class Untils {


    public  void doget(String url){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request build = new Request.Builder().url(url).build();
        okHttpClient.newCall(build).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();
                Log.i("11111111111",string);
            }
        });
    }
    //方式2
    public  void doget(String url, Map<String,String> map){

        if (map!=null){
           url+="?";
            for (Map.Entry<String, String> entry : map.entrySet() ){
                String key = entry.getKey();
                String value = entry.getValue();
                url=url+key+"="+value+"&";

            }
            //去掉尾部的&
            String new_str = url.substring(0, url.length() - 1);
            OkHttpClient okHttpClient = new OkHttpClient();
            Request build = new Request.Builder().url(new_str).build();
            okHttpClient.newCall(build).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();
                    Log.i("222222222222",string);
                }
            });
        }

    }


    //33333333333333333333333
    public void dopost(String url,String name,String pass){
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("mobile",name);
        builder.add("password",pass);
        FormBody formBody = builder.build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        okHttpClient.newCall(request).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();
                Log.i("3333333333333",string);
            }
        });
    }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页