当前位置:   article > 正文

网络请求框架----okhttp3_okhttp3.request

okhttp3.request

一、okhttp3的使用

1、添加依赖

  1. compile 'com.squareup.okhttp3:okhttp:3.7.0'
  2. compile 'com.squareup.okio:okio:1.12.0'

2、基本用法

    (1)get异步请求

  1. private void get(String url){
  2. OkHttpClient client = new OkHttpClient().newBuilder().build();
  3. Request request = new Request.Builder()
  4. .url(url)
  5. .header("","")
  6. .build();
  7. Call call = client.newCall(request);
  8. call.enqueue(new Callback() {
  9. @Override
  10. public void onFailure(Call call, IOException e) {
  11. }
  12. @Override
  13. public void onResponse(Call call, Response response) throws IOException {
  14. }
  15. });
  16. }

(2)post异步请求(参数为Map)

  1. private void post(String url, Map<String, String> maps) {
  2. OkHttpClient client = new OkHttpClient().newBuilder().build();
  3. if (maps == null) {
  4. maps = new HashMap<>();
  5. }
  6. Request.Builder builder = new Request.Builder()
  7. .url(url);
  8. if (maps != null && maps.size() > 0) {
  9. FormBody formBody = new FormBody.Builder();
  10. for (String key : maps.keySet()) {
  11. body.add(key, paramsMap.get(key));
  12. }
  13. builder.post(formBody.builder());
  14. }
  15. Request request = builder.build();
  16. Call call = client.newCall(request);
  17. call.enqueue(new Callback() {
  18. @Override
  19. public void onFailure(Call call, IOException e) {
  20. }
  21. @Override
  22. public void onResponse(Call call, Response response) throws IOException {
  23. }
  24. });
  25. }

(3)post异步请求(参数为json)

  1. private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  2. public void post(String url,JsonObject json) {
  3. OkHttpClient client = new OkHttpClient();
  4. RequestBody body = RequestBody.create(JSON, json);
  5. Request request = new Request.Builder()
  6. .url("")
  7. .post(body)
  8. .build();
  9. Call call = client.newCall(request);
  10. call.enqueue(new Callback() {
  11. @Override
  12. public void onFailure(@NotNull Call call, @NotNull IOException e) {
  13. }
  14. @Override
  15. public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
  16. }
  17. });
  18. }

(4)上传文件  MutipartBody

  1. private void postFile(){
  2. OkHttpClient client = new OkHttpClient().newBuilder().build();
  3. RequestBody requestBody =
  4. RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8") , new File(""));
  5. String name = "fileName"; //文件名称
  6. try {
  7. name = URLEncoder.encode(name, "UTF-8"); //文件名称编码,防止出现中文乱码
  8. } catch (UnsupportedEncodingException e1) {
  9. //TODO
  10. }
  11. //定义请求体,前面三个为表单中的string类型参数,第四个为需要上传的文件
  12. MultipartBody mBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
  13. .addFormDataPart("fileSize" , "12123")
  14. .addFormDataPart("time" , "234234")
  15. .addFormDataPart("name" , name)
  16. .addFormDataPart("file" , name , requestBody)
  17. .build();
  18. Request request = new Request.Builder().url("").header("","").post(mBody).build();
  19. Call call = client.newCall(request);
  20. call.enqueue(new Callback() {
  21. @Override
  22. public void onFailure(Call call, IOException e) {
  23. }
  24. @Override
  25. public void onResponse(Call call, Response response) throws IOException {
  26. }
  27. });
  28. }

3、异步请求结果

  1. call.enqueue(new Callback() {
  2. @Override
  3. public void onFailure(Call call, IOException e) {
  4. }
  5. @Override
  6. public void onResponse(Call call, Response response) throws IOException {
  7. //结果在工作线程中,不能直接更新UI
  8. //如果希望返回的是字符串
  9. final String responseData=response.body().string();
  10. //如果希望返回的是二进制字节数组
  11. byte[] responseBytes=response.body().bytes();
  12. //如果希望返回的是inputStream,有inputStream我们就可以通过IO的方式写文件.
  13. InputStream responseStream=response.body().byteStream();
  14. }
  15. });

注: 异步请求callback回调是在工作线程中,所以不能直接更新UI,可以通过Looper.myLooper()==Looper.getMainLooper()   进行简单判断,解决方式可以使用Handler

 

4、Request的参数RequestBody

    RequestBody是抽象类,FormBody和MultipartBody是其子类。

  1. Request request = new Request.Builder()
  2. .url("")
  3. .header("", "")
  4. .post(RequestBody body)
  5. .build();

 

  1. //RequestBody的创建
  2. RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8") , new File(""));
  3. MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
  4. RequestBody imgBody = MultipartBody.create(MEDIA_TYPE_PNG, new Flie());
  5. //FormBody的创建
  6. FormBody body = new FormBody.Builder()
  7. .add("", "")
  8. .build();
  9. //MultipartBody的创建
  10. MultipartBody body=new MultipartBody.Builder()
  11. .addFormDataPart("key","value")
  12. .addFormDataPart("name","fileName",RequestBody body)
  13. .build();

5、自定义拦截器

(1)日志拦截器

  1. public class LogInterceptor implements Interceptor {
  2. @NotNull
  3. @Override
  4. public Response intercept(@NotNull Chain chain) throws IOException {
  5. Request request = chain.request();
  6. Headers headers = request.headers();
  7. Set<String> names = headers.names();
  8. Iterator<String> iterator = names.iterator();
  9. //打印请求路径
  10. Log.d(getClass().getSimpleName(), "url=" + request.url());
  11. //打印header
  12. Log.d(getClass().getSimpleName(), "=======headers start=====");
  13. while (iterator.hasNext()) {
  14. String next = iterator.next();
  15. Log.d(getClass().getSimpleName(), next + ":" + headers.get(next));
  16. }
  17. Log.d(getClass().getSimpleName(), "=======headers end=====");
  18. //打印post方式请求参数
  19. String method = request.method();
  20. if (method.equals("POST")) {
  21. RequestBody body = request.body();
  22. if (body != null) {
  23. if (body.contentType() != null) {
  24. Log.d(getClass().getSimpleName(), "contentType:" + body.contentType().toString());
  25. }
  26. Log.d(getClass().getSimpleName(), "=======params start=====");
  27. if (body instanceof FormBody) {
  28. FormBody formBody = (FormBody) body;
  29. for (int i = 0; i < formBody.size(); i++) {
  30. Log.d(getClass().getSimpleName(), formBody.name(i) + ":" + formBody.value(i));
  31. }
  32. }
  33. Log.d(getClass().getSimpleName(), "=======params end=====");
  34. }
  35. }
  36. //打印response
  37. Response response = chain.proceed(request);
  38. ResponseBody body = response.body();
  39. if (body != null) {
  40. Log.d(getClass().getSimpleName(), "response:" + body.toString());
  41. }
  42. return response;
  43. }
  44. }

(2)添加header拦截器

  1. /*
  2. * 添加请求头
  3. */
  4. public class HeadInterceptor implements Interceptor {
  5. @NotNull
  6. @Override
  7. public Response intercept(@NotNull Chain chain) throws IOException {
  8. Request request = chain.request();
  9. request = request.newBuilder()
  10. .addHeader("key", "value")
  11. .build();
  12. Headers headers = request.headers();
  13. Set<String> names = headers.names();
  14. Iterator<String> iterator = names.iterator();
  15. while (iterator.hasNext()) {
  16. String next = iterator.next();
  17. Log.d("aaa", next + ":" + headers.get(next));
  18. }
  19. Response response = chain.proceed(request);
  20. return response;
  21. }
  22. }
<
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号