美文网首页
Android OKHTTP3的GET和POST方法(带basi

Android OKHTTP3的GET和POST方法(带basi

作者: Observer_____ | 来源:发表于2018-03-12 19:46 被阅读0次

使用前需要在Gradle Script中的build gradle中引入:

compile 'com.squareup.okio:okio:1.13.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'

  1. GET
            //创建OkHttpClient对象
            OkHttpClient okHttpClient  = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10,TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .build();

            final Request request = new Request.Builder()
                    .url("http://172.20.192.168:8080/getbookByFrom?name=android基础&price=50")//请求的url
                    .get()//设置请求方式,get()/post()  查看Builder()方法知,在构建时默认设置请求方式为GET
                    .build(); //构建一个请求Request对象

            //创建/Call
            Call call = okHttpClient.newCall(request);
            //加入队列 异步操作
            call.enqueue(new Callback() {
                //请求错误回调方法
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println("连接失败");
                }
                //异步请求(非主线程)
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.code()==200) {
                        System.out.println(response.body().string());
                    }             
            });
  1. POST(json方式)
 OkHttpClient okHttpClient  = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();

        Book book = new Book();
        book.setName("android基础");
        book.setPrice(59);
        //使用Gson 添加 依赖 compile 'com.google.code.gson:gson:2.8.1'
        Gson gson = new Gson();
        //使用Gson将对象转换为json字符串
        String json = gson.toJson(book);

        //MediaType  设置Content-Type 标头中包含的媒体类型值
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
        , json);

         Request request = new Request.Builder()
                .url("http://172.20.192.168:8080/getbookByJson")//请求的url
                .post(requestBody)
                .build();

        //创建/Call
        Call call = okHttpClient.newCall(request);
        //加入队列 异步操作
        call.enqueue(new Callback() {
            //请求错误回调方法
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("连接失败");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }
        });

关于将对象转换为json字符串,除了使用Gson还可以用JSONObject:

       public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8");
       JSONObject jsonObject = new JSONObject();
       try {
            //example: {'likes':['体育','政治'...]}
            jsonObject.put("likes",selectedThemes);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建一个RequestBody(参数1:数据类型 参数2传递的json串)
        RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());

开发过程中遇到传json需要带上authentication的问题,然后在Stack Overflow上找到了解决方法——使用Interceptor。

import java.io.IOException;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class BasicAuthInterceptor implements Interceptor {

    private String credentials;

    public BasicAuthInterceptor(String user, String password) {
        this.credentials = Credentials.basic(user, password);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request authenticatedRequest = request.newBuilder()
                    .header("Authorization", credentials).build();
        return chain.proceed(authenticatedRequest);
    }
}

这样就把username和password放进了authentication里。然后把这个Interceptor加到OkHttpClient就可以了。

OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new BasicAuthInterceptor(username, password))
    .build();

相关文章

  • Android OKHTTP3的GET和POST方法(带basi

    使用前需要在Gradle Script中的build gradle中引入: compile 'com.square...

  • OkHttp3简单封装

    简单封装了OkHttp3的请求方法,包含:GET、POST、上传文件、下载文件。项目地址:https://gith...

  • 网络相关问题

    (1)Http Get和Post方法 GET:无副作用,幂等,不可带 Request BodyPUT:副作用,幂等...

  • js知识点2

    get() 和 post()方法

  • GetPost

    Http 方法:Get/Post 两种最常用的HTTP方法:Get和Post[https://www.jiansh...

  • OkHttpUtils工具类

    1,导入依赖包: 2,在manifest中添加: 3,代码如下: okhttp3简单封装GET和POST请求工具类...

  • Okhttp3封装

    封装OKHTTP3一般的get,post请求,和文件下载,图片和多文件的上传。 参考链接:https://blog...

  • requests

    requests.get()requests.post() 默认的get和post方法均为status_code为...

  • ajax原生兼容

    总结一下JavaScript原生ajax写法 有get和post两种方法,写法差异不大 POST方法: GET方法

  • 2018-10-19——请求方法

    常见的请求方法有两种:GET和POST GET和POST请求方法有如下区别: ①GET请求中的参数包含着URL里面...

网友评论

      本文标题:Android OKHTTP3的GET和POST方法(带basi

      本文链接:https://www.haomeiwen.com/subject/aqjofftx.html