注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

天朝布衣田中码农参上

苦逼码农的点点滴滴,请多多指教!

 
 
 

日志

 
 
 
 

OkHttp的简易使用用法  

2017-09-28 10:11:26|  分类: Android |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
最近在配合一个安卓项目,使用到了OkHttp开源包,相信大家对OkHttp也是相当的熟悉了,毕竟是Square的东西,对于其种种优点不多说,只是使用它封装类来进行简单的GET/POST请求感觉有点牛刀杀鸡[引用这些封装类包让APP体积扩大],所以简单的看了下文档,写了下相应的简陋调用代码。
在使用之前,请记住引用okhttp和okio两个包,它们的下载地址分别为:okhttp okio
okhttp官网地址:https://github.com/square/okhttp
Android Studio的用户,可以选择添加[gradle]:
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.okio:okio:1.5.0'

package com.593668.test;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.MultipartBody.Builder;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class Test {

OkHttpClient client = new OkHttpClient();
public static void main(String[] args) throws IOException {
Test tt=new Test();
//无需提交参数请求
//System.out.printf(tt.get("http://593668.com/gettoken.json"));
//此下是提交JSON
//System.out.printf(tt.postJson("http://593668.com/insureresult.json","{\"site\":\"593668.com\",\"token\":\"593668.com\"}"));
Map<String, String> map = new TreeMap<String, String>();
String key, value;
map.put("site", "593668.com");
map.put("token", "593668.com");
//以POST提交参数
//System.out.printf(tt.post("http://593668.com/getuserinfo.json",map));
//以POST提交上付文件
System.out.printf(tt.postFile("http://593668.com/upload.json",map,"D:/tt/wall/0001.jpg"));
}

//GET同步
String get(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}


//POSTJSON同步
String postJson(String url, String json) throws IOException {
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
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);
}
}

//POST同步
String post(String url, Map<String, String> map) throws IOException {
Builder builder=new MultipartBody.Builder().setType(MultipartBody.FORM);
Iterator<String> iter = map.keySet().iterator();
//设置参数
while (iter.hasNext()) {
String key=iter.next();
builder.addFormDataPart(key, (String) map.get(key));
}
RequestBody formBody = builder.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}

//POSTFILE同步
String postFile(String url, Map<String, String> map, String filename) throws IOException {
Builder builder=new MultipartBody.Builder().setType(MultipartBody.FORM);
Iterator<String> iter = map.keySet().iterator();
//设置参数
while (iter.hasNext()) {
String key=iter.next();
builder.addFormDataPart(key, (String) map.get(key));
}
RequestBody formBody = builder.build();
//这里再加入相应的上传文件
formBody=builder.addFormDataPart("files", filename, formBody).build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
}

当然这些都是同步调用方法,可能在某些项目中并不实用,那么将之改成异步也并不是太过困难的事。

//GET异步
void getAsyn(String url){
Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
call.enqueue(new Callback()
{
@Override
public void onFailure(Call arg0, IOException arg1) {
//失败
}

@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
//成功执行回调
if(arg1.isSuccessful()){
System.out.printf(arg1.body().string());
}
}
});
return;
}

//POSTJSON异步
void postJsonAsyn(String url, String json) throws IOException {
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
Call call = client.newCall(request);
call.enqueue(new Callback()
{
@Override
public void onFailure(Call arg0, IOException arg1) {
//失败
}

@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
//成功执行回调
if(arg1.isSuccessful()){
System.out.printf(arg1.body().string());
}
}
});
return;
}

//POST异步
void postAsyn(String url, Map<String, String> map) throws IOException {
Builder builder=new MultipartBody.Builder().setType(MultipartBody.FORM);
Iterator<String> iter = map.keySet().iterator();
//设置参数
while (iter.hasNext()) {
String key=iter.next();
builder.addFormDataPart(key, (String) map.get(key));
}
RequestBody formBody = builder.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response response = client.newCall(request).execute();
Call call = client.newCall(request);
call.enqueue(new Callback()
{
@Override
public void onFailure(Call arg0, IOException arg1) {
//失败
}

@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
//成功执行回调
if(arg1.isSuccessful()){
System.out.printf(arg1.body().string());
}
}
});
return;
}

//POSTFILE异步
void postFileAsyn(String url, Map<String, String> map, String filename) throws IOException {
Builder builder=new MultipartBody.Builder().setType(MultipartBody.FORM);
Iterator<String> iter = map.keySet().iterator();
//设置参数
while (iter.hasNext()) {
String key=iter.next();
builder.addFormDataPart(key, (String) map.get(key));
}
RequestBody formBody = builder.build();
//这里再加入相应的上传文件
formBody=builder.addFormDataPart("files", filename, formBody).build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback()
{
@Override
public void onFailure(Call arg0, IOException arg1) {
//失败
}

@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
//成功执行回调
if(arg1.isSuccessful()){
System.out.printf(arg1.body().string());
}
}
});
return;
}

非常简单的使用,当然如果需要更多的功能,可以自行扩展,网上也有网友写好了封装类,可以直接去调用。
  评论这张
 
阅读(0)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018