OkHttp3 使用

android studio环境配置

在Module的build.gradle文件中增加依赖包:

dependencies {
    ···
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
}

基本使用

主要有发Get和Post请求两种

Get请求

新建工程。先看代码

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    Response response;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OkHttpClient client = new OkHttpClient();
                            Request request = new Request.Builder().url("https://raw.github.com/square/okhttp/master/README.md").build();
                            response = client.newCall(request).execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
        ).start();
        try {
            Log.v("mylog", response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

结果如下:

OkHttp3 使用_第1张图片
Paste_Image.png

其中由于UI线程不能发网络请求,必须开新的线程来进行网络处理。
其中主要代码是:

try {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url("https://raw.github.com/square/okhttp/master/README.md").build();
    Response response = client.newCall(request).execute();
    Log.v("mylog", response.body().string());
} catch (Exception e) {
    e.printStackTrace();
}

Response类:

(1)isSuccessful() 方法

public boolean isSuccessful()   //如果返回码是[200..300),该函数则返回true。

(2)body() 方法

Response response;
ResponseBody responseBody = response.body()      //返回ResponseBody类
String string = responseBody.string()  

ResponseBody类的string方法,将response作为string返回。

Post请求

新建工程。先看代码

public class MainActivity extends AppCompatActivity {
    Response response;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            testPost();
                            try {
                                if(response.isSuccessful()){
                                    Log.v("mylog", response.body().string());
                                    Log.v("mylog", response.header("Set-Cookie"));
                                }else {
                                    Log.v("mylog", "Unexpected code " + response);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
        ).start();
    }

    public String GetJson(String PhoneNum, String VerifyCode) {
        JSONObject jsn_login = new JSONObject();
        try{
            jsn_login.put("phoneNo",PhoneNum);
            jsn_login.put("requestOtp",VerifyCode);
        }catch (Exception e){}
        return jsn_login.toString();
    }


    public void testPost() throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, GetJson("11111111111","1234"));
        Request request = new Request.Builder()
                .url("http://localhost:8080/login.do")
                .header("User-Agent", "OkHttp Headers.java")
                .addHeader("Accept", "application/json; q=0.5")
                .post(body)
                .build();
        response = client.newCall(request).execute();
    }
}

(1)设置请求头的方法:
1)对于header(String name, String value)方法,使用name和value设置一个头信息,如果请求中已经存在响应的信息那么直接替换掉。
2)而addHeader(String name, String value),如果请求头中已经存在name的name-value,那么还会继续添加,请求头中便会存在多个name相同而value不同的“键值对”。

(2)获取返回头的方法:
1)response.header("name")方法:如果header中有重复的,则返回最后出现的value。如果没有值,那么header(name)将返回null。

response.header("Set-Cookie")``` 代表获取cookie。

2)response.headers()方法,获取所有的header:返回一个list。为了获取所有的Header,Headers类支持按index访问。

Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}

(3)Post请求提交Json数据
1)首先新建一个MediaType
MediaType代表的就是请求包体内容的类型。
例如,MediaType.parse("application/json; charset=utf-8");这个就带表请求体的类型为JSON格式的。
2)再通过 RequestBody.create(MediaType, JSONDATA);的方法来创建一个 RequestBody
3)最后通过Request.Builder().Post(RequestBody)方法来加入post数据。

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
     RequestBody body = RequestBody.create(JSON, json);
      Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
      Response response = client.newCall(request).execute();
    f (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

(4)Post请求提交键值对
具体方法如下:

OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
     RequestBody formBody = new FormEncodingBuilder()
    .add("platform", "android")
    .add("name", "bug")
    .add("subject", "XXXXXXXXXXXXXXX")
    .build();
 
      Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
 
      Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

(5)Post方式提交文件

public static final MediaType MEDIA_TYPE_MARKDOWN
  = MediaType.parse("text/x-markdown; charset=utf-8");
 
private final OkHttpClient client = new OkHttpClient();
 
public void run() throws Exception {
    File file = new File("README.md");
 
    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
        .build();
 
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
 
    System.out.println(response.body().string());
}

(6)Post方式提交分块请求
MultipartBuilder可以构建复杂的请求体,与HTML文件上传形式兼容。多块请求体中每块请求都是一个请求体,可以定义自己的请求头。这些请求头可以用来描述这块请求,例如他的Content-Disposition。如果Content-Length和Content-Type可用的话,他们会被自动添加到请求头中。

private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
 
private final OkHttpClient client = new OkHttpClient();
 
public void run() throws Exception {
    // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
    RequestBody requestBody = new MultipartBuilder()
        .type(MultipartBuilder.FORM)
        .addPart(
            Headers.of("Content-Disposition", "form-data; name=\"title\""),
            RequestBody.create(null, "Square Logo"))
        .addPart(
            Headers.of("Content-Disposition", "form-data; name=\"image\""),
            RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
        .build();
 
    Request request = new Request.Builder()
        .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
        .url("https://api.imgur.com/3/image")
        .post(requestBody)
        .build();
 
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
 
    System.out.println(response.body().string());
}

异步Get请求

先看代码

public class MainActivity extends AppCompatActivity {
    Response response;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        testAsyncGet();
    }

    public void testAsyncGet() {
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();
        System.out.println(request);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.v("mylog", "call = [" + call + "], response = [" + response + "]");
                if (!response.isSuccessful()) {
                    throw new IOException("" + response);
                }

                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    Log.v("mylog", headers.name(i) + ": " + headers.value(i));
                }

                System.out.println(response.body().string());
            }
        });
    }
}

输出如下:

OkHttp3 使用_第2张图片
Paste_Image.png

https://github.com/square/okhttp/wiki/Recipes
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html
http://blog.csdn.net/biezhihua/article/details/50603624

你可能感兴趣的:(OkHttp3 使用)