okhttp简单的应用

okhttp官网http://square.github.io/okhttp/
okhttp的git仓库https://github.com/square/okhttp
okhttp的使用方法https://github.com/square/okhttp/wiki/Recipes

一、配置
android studio中,在app下的build.gradle文件中添加:compile ‘com.squareup.okhttp:okhttp:2.6.0’(2.6.0为版本号,最好写最新的),如下:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'

    compile 'com.squareup.okhttp:okhttp:2.6.0'
}

二、Get方法(获取数据):

看代码

/**
 * okhttp Get方法获取数据
 * @param url
 * @return
 */
public static void getData(String url){
  try {
   //请求
   Request request = new Request.Builder()
        .url(url)
        .build();
   /**
    * 方法一
    * 同步的
    */
//Response response = okHttpClient.newCall(request).execute();
//
//     //判断是否请求成功
//     if (!response.isSuccessful()) throw new Exception("Unexpected code:"+response);
//
//     Headers headers = response.headers();
//     for (int i = 0;i<headers.size();i++){
//         System.out.println("Get请求结果:"+headers.name(i)+":"+headers.value(i));
//            }
//
//            System.out.println("Get请求结果(字符串):"+response.body().toString());

  /**
   * 方法二
   * 异步的,即enqueue是运行在子线程中的,回调函数Callback()中
   * 的两个方法也是运行在子线程的
   */
  okHttpClient.newCall(request).enqueue(new Callback() {
    //此方法是在用户取消此操作、请求超时等情况下调用
    @Override
    public void onFailure(Request request, IOException e) {
         e.printStackTrace();
   }

   //此方法是在成功地从服务端请求到了数据时调用
     @Override
     public void onResponse(Response response) throws IOException {
       //在此对response进行处理
       //判断是否请求成功
       if (!response.isSuccessful()) throw new IOException("Unexpected code:"+response);

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

      System.out.println("Get请求结果(字符串):"+response.body().toString());
                }
            });

        }catch (Exception e){
            e.printStackTrace();
        }
    }

三、下载图片:

/**
 * 下载图片是得到图片的字节数组,然后在转换成bitmap
 */
private static byte[] getBytesData(String url) throws Exception {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = okHttpClient.newCall(request).execute();

        byte[] imageBytes = response.body().bytes();

        return imageBytes;
    }

四、Post方法:

/**
 * Post方法就是比Get方法多了一个post(requestBody),多一个
 * RequestBody
 * @param url
 * @param jsonStr jsonStr是通过JSONStringer构成的JSON格式  
 * 的数据,然后转换成字符串
 */
 private static String getJsonData(String url, String jsonStr) throws Exception {
 RequestBody body = RequestBody.create(JSON, jsonStr);
 Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
 Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
      String s = response.body().string();
      //请求的结果
      return s;
  } else {
    throw new IOException("Unexpected code " + response);
      }
}

五、上传图片或文件

 /**
  * 上传图片
  * @param url 上传图片的地址url
  * @param path 手机中图片或文件的路径
  */
private static String uploadPicture(String url, String path) throws Exception {
    File file;
    file = new File(path);
    //构造请求体
    RequestBody requestBody = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE, file))
                .build();

    Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

    Response response = okHttpClient.newCall(request).execute();
    if (response.isSuccessful()) {
      String s = response.body().string();
      //上传图片的结果
      return s;
  } else {
    throw new IOException("Unexpected code " + response);
      }
 }

上传文件或图片是的进度条,请参考:1、http://46aae4d1e2371e4aa769798941cef698.devproxy.yunshipei.com/djk_dong/article/details/48179315/
2、http://blog.csdn.net/sbsujjbcy/article/details/48194701

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值