您的位置:首页 > 理论基础 > 计算机网络

okhttp简单的应用

2015-12-04 17:09 579 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: