android网络框架之OKhttp[1]一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支付[Squar(http://baike.baidu.com/item/Square/65870)公司贡献(该公司还贡献了Picasso)[2]用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient,现在已经打不出来)
下载地址:okhttp ,要翻墙下载,必须下载okhttp以及okio两个jar包。
示例代码:
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* 利用okhtto实现发送网络请求
* @author zhaotong
*
*/
public class ServiceTools {
public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
private static OkHttpClient client=new OkHttpClient();
//发送post请求
public static String postTargetData(String url ,String content )
{
String result=null;
RequestBody body=RequestBody.create(JSON,content);
Request request=new Request.Builder().url(url).post(body).build();
Response res=null;
try {
res = client.newCall(request).execute();
result=res.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
//发送get请求
public static String getTargetData(String url)
{
String result=null;
Request request=new Request.Builder().url(url).build();
Response res=null;
try {
res=client.newCall(request).execute();
result=res.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}