OkHttpClient
用法1:自定义缓存
OkHttpClient httpclient = new OkHttpClient.Builder() .cache(new Cache(new File("cacheDirectory"), new Long(10 * 1024 * 1024))) .build();
用法2:当出现缓存冲突时(常用)
OkHttpClient httpclient = new OkHttpClient();
提交请求:
httpclient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { }});
用法2:
Response respOnse= httpclient.newCall(request).execute();
Request类
Request request = new Request.Builder() .url("www.baidu.com") .header("User-Agent", "OkHttp Header1.java")//键值对,唯一 .header("User-Agent", "OkHttp Header2.java")//再次使用相同字段,值被覆盖 .addHeader("Accept", "application/json; q=0.5")//添加不覆盖,这时又两个“key”,值分别为"value2"、"value3" .addHeader("Accept", "application/vnd.github.v3+json")//add几个就增加几个 .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), "postBody")) //RequestBody内容可以很丰富,第二个参数可以是多种类型的字符集 .build();
RequestBody
需要MediaType
RequestBody requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"),body);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json);
MediaType mediaType = MediaType.parse("image/png");
RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return MediaType.parse("text/x-markdown; charset=utf-8");; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8("Numbers\n"); sink.writeUtf8("-------\n"); for (int i = 2; i <= 997; i++) { sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i))); } } private String factor(int n) { for (int i = 2; i ; i++) { int x = n / i; if (x * i == n) return factor(x) + " × " + i; } return Integer.toString(n); }}; 用法3:
用法3:
RequestBody formBody = new FormBody.Builder() .add("search", "Jurassic Park") .addEncoded("encoded","utf-8") .build();
用法4:
RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addPart(Header,RequestBody)//添加包含头和body的Part .addFormDataPart("title", "Square Logo")//表单中添加表单 .addFormDataPart("image", "logo-square.png", RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png"))) .build();
MediaType
配置请求类型
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
Response
用法1:
ResponseBody respOnseBody= response.body();response.body().string();response.code();//HTTP status coderesponse.header("key1");response.header("key2");response.headers("key1");response.networkResponse();
还有很多实用的方法。