OkHttp getand post 请求

来源:互联网 发布:淘宝靠谱的阿迪代购 编辑:程序博客网 时间:2024/05/03 03:01




okHttp   2.0请求方式

package utils;


import android.util.Log;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

/**
 * Created by lenovo on 2017/1/4.
 * OkHttp的异步请求
 */
public final class YiBuQingQiu {

    private static String json = null;

    public static String GetQingQiu(String url) {

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
        //创建一个Request
        final Request request = new Request.Builder()
                .url(url)
                .build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
            }

            @Override
            public void onResponse(final Response response) throws IOException {
                json = response.body().string();
            }
        });
        return json;
    }

    public static String PostQingQiu(String url, String page) {
        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
        //设置参数
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("page", page);
        //创建一个Request
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        //请求加入调度
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                json = response.body().string();
            }
        });
        return json;
    }

}


okHttp   3.0请求方式



      post 请求


String path = "http://v.juhe.cn/weixin/query";HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();//获得OkHttpClient 对象OkHttpClient client = new OkHttpClient.Builder()        .addInterceptor(interceptor)        .addNetworkInterceptor(interceptor)        .build();RequestBody body = new FormBody.Builder().add("key", "").build();Request request = new Request.Builder().url(path).post(body).build();client.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();
}});

Get请求



1 0
原创粉丝点击