网络访问之OkHttp

来源:互联网 发布:php tp框架邮箱验证码 编辑:程序博客网 时间:2024/05/29 10:18

1、github地址

https://github.com/square/okhttp

官网

http://square.github.io/okhttp/

构建引入:

compile 'com.squareup.okhttp3:okhttp:3.7.0'

网络权限

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

2、get请求

OkHttpClient mOkHttpClient=new OkHttpClient();//        Request.Builder requestBuilder = new Request.Builder().url("http://www.baidu.com");//        //可以省略,默认是GET请求//        requestBuilder.method("GET",null);//        Request request = requestBuilder.build();Request request = new Request.Builder().url("http://www.baidu.com").method("GET",null).build();Call mcall= mOkHttpClient.newCall(request);mcall.enqueue(new Callback() {    @Override    public void onFailure(Call call, IOException e) {    }    @Override    public void onResponse(Call call, Response response) throws IOException {        if (null != response.cacheResponse()) {            String str = response.cacheResponse().toString();        } else {            response.body().string();            String str = response.networkResponse().toString();        }        runOnUiThread(new Runnable() {            @Override            public void run() {                Toast.makeText(MainActivity.this, "请求成功", Toast.LENGTH_SHORT).show();            }        });    }});

post请求

OkHttpClient mOkHttpClient= new OkHttpClient();RequestBody formBody = new FormBody.Builder()        .add("canshu", "value")        .build();Request request = new Request.Builder()        .url("")        .post(formBody)        .build();Call call = mOkHttpClient.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 str = response.body().string();        runOnUiThread(new Runnable() {            @Override            public void run() {                Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();            }        });    }});

如果上传文件,要定义文件类型:

public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
0 0
原创粉丝点击