1、Retrofit是什么?
Retrofit是目前最火的网络请求库,Retrofit与okhttp共同出自于Square公司,retrofit就是对okhttp做了一层封装,把网络请求都交给给了Okhttp。
2、本示例演示下载百度的html数据,展示到webview控件上,结果截图如下:
![结果](https://img-blog.csdn.net/20170222150528184?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTQxMjIzNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
2.1 引入Retrofit
compile 'com.squareup.retrofit2:retrofit:2.2.0'
2.2 定义一个接口,返回Call
/**
* 定义一个接口
*/
public interface IBaiduService
{
@GET("/")
Call<String> getBaiduHtml();
}
2.3 创建Retrofit对象,指定url地址,获取返回结果
Retrofit retrofit = new Retrofit.Builder().baseUrl("http:www.baidu.com").addConverterFactory(new Converter.Factory()
{
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit)
{
return new Converter<ResponseBody, String>()
{
@Override
public String convert(ResponseBody value) throws IOException
{
return value.string();
}
};
}
}).build();
IBaiduService baiduService = retrofit.create(IBaiduService.class);
Call<String> call = baiduService.getBaiduHtml();
call.enqueue(new Callback<String>()
{
@Override
public void onResponse(Call<String> call, Response<String> response)
{
webView.loadData(response.body(),"text/html; charset=UTF-8", null);
}
@Override
public void onFailure(Call<String> call, Throwable t)
{
}
});